search
HomeWeb Front-endFront-end Q&Anode require what does it mean

node require what does it mean

Oct 18, 2022 pm 05:51 PM
nodejsnoderequire functionrequire()

require in node is a function that accepts a parameter, the formal parameter is named id, and the type is String; the require function can import modules, JSON files, and local files; the module can be accessed from Exported from "node_modules", "local module" or "JSON file", the path will be for the "__dirname" variable or the current working directory.

node require what does it mean

The operating environment of this tutorial: Windows 7 system, nodejs version 18.4.0, Dell G3 computer.

What does node require mean?

The specific usage of the require function in Nodejs

Instructions

This article refers to the Node official website document version. v11.12.0.

This article mainly analyzes the results obtained when require imports JSON and js files in Nodejs. It also briefly touches on the usage of module export module.exports and exports in Nodejs.

Introduction

In the process of reading the webpack source code, I saw the following line of code:

const version = require("../package.json").version

So This leads to the study of require in Nodejs.

require introduction

In the Node.js documentation, the relevant documentation for require is in the Modules directory and belongs to the Nodejs module part of the system.

require is a function. This conclusion can be verified through typeof or Object.prototype.toString.call():

console.log(require) // 输出:Function
console.log(Object.prototype.toString.call(require) // 输出:[object Function]

By printing require directly, you can find that there are several static properties mounted under the require function. These static properties can also be The relevant instructions can be found directly in the official documentation of Nodejs:

{ [Function: require]
 resolve: { [Function: resolve] paths: [Function: paths] },
 main:
  Module {
   id: '.',
   exports: {},
   parent: null,
   filename: '/Users/bjhl/Documents/webpackSource/index.js',
   loaded: false,
   children: [],
   paths:
   [ '/Users/bjhl/Documents/webpackSource/node_modules',
    '/Users/bjhl/Documents/node_modules',
    '/Users/bjhl/node_modules',
    '/Users/node_modules',
    '/node_modules' ] },
 extensions:
  [Object: null prototype] { '.js': [Function], '.json': [Function], '.node': [Function] },
 cache:
  [Object: null prototype] {
   '/Users/bjhl/Documents/webpackSource/index.js':
   Module {
    id: '.',
    exports: {},
    parent: null,
    filename: '/Users/bjhl/Documents/webpackSource/index.js',
    loaded: false,
    children: [],
    paths: [Array] } } }

require function static attributes

will be added in detail later.

require use

You can see the following instructions about require in the official website documentation:

require(id)# Added in: v0.1.13 id module name or path Returns: exported module content Used to import modules, JSON, and local files. Modules can be imported from node_modules. Local modules and JSON files can be imported using a relative path (e.g. ./, ./foo, ./bar/baz, ../foo) that will be resolved against the directory named by __dirname (if defined) or the current working directory.

At the same time, three methods of using require are also given:

// Importing a local module:
const myLocalModule = require('./path/myLocalModule');

// Importing a JSON file:
const jsonData = require('./path/filename.json');

// Importing a module from node_modules or Node.js built-in module:
const crypto = require('crypto');

From the above documents, the following information can be drawn:

  • require accepts one parameter, The formal parameter is named id and its type is String.

  • The require function returns the contents of the module, and the type is arbitrary.

  • The require function can import modules, JSON files, and local files. Modules can be exported from node_modules, local modules, JSON files via a relative path against the __dirname variable (if defined) or the current working directory.

require practice

Here we will discuss the practical conclusions of require in categories.

requireImport JSON

JSON is a syntax for serializing objects, arrays, numbers, strings, Boolean values, and null .

At the beginning of the article, it was mentioned that the version attribute in the package.json file is read through the require("./package.json") file. Here we will try to import the info.json file and view related information.

The file structure directory is as follows:

.
├── index.js
└── info.json

Modify the content of the info.json file to:

{
  "name": "myInfo",
  "hasFriend": true,
  "salary": null,
  "version": "v1.0.0",
  "author": {
    "nickname": "Hello Kitty",
    "age": 20,
    "friends": [
      {
        "nickname": "snowy",
        "age": 999
      }
    ]
  }
}

In info.json, it contains strings, Boolean values, and null , numbers, objects and arrays.

Modify the content of index.js as follows and run the command node index.js in the current terminal, and get the following results:

const info = require("./info.json")
console.log(Object.prototype.toString.call(info)) // [object Object]
console.log(info.version) // v1.0.0
console.log(info.hasFriend) // true
console.log(info.salary) // null
console.log(info.author.nickname) // Hello Kitty
console.log(info.author.friends) // [ { nickname: 'snowy', age: 999 } ]

As you can see, when require imports a JSON file, it returns An object, Nodejs can directly access all properties in this object, including String, Boolean, Number, Null, Object, and Array. My personal guess is that a method similar to JSON.parse() may be used here.

Through this conclusion, we also came up with an idea, which is to pass in the JSON file through the require method to read certain values. For example, at the beginning of the article, webpack obtained the version value by reading the package.json file. .

requireImport local js files

The file structure directory is as follows:

.
├── index.js
├── module_a.js
└── module_b.js

In the index.js file, module_a is imported in order and module_b and assign values, and then print these two variables, the content is as follows:

console.log("*** index.js开始执行 ***")
const module_a = require("./module_a")
const module_b = require("./module_b")
console.log(module_a, "*** 打印module_a ***")
console.log(module_b, "*** 打印module_b ***")
console.log("*** index.js结束执行 ***")

In the module_a file, module.exports or exports is not specified, but an asynchronous execution statement setTimeout is added, the content is as follows:

In the
console.log("** module_a开始执行 **")
let name = "I'm module_a"
setTimeout(() => {
  console.log(name, "** setTimeout打印a的名字 **")
}, 0)
console.log("** module_a结束执行 **")

module_b file, module.exports is specified (you can also change it to exports.name, but you cannot directly use exports to equal an object, because exports and module.exports actually point to an address and reference the same object , if exports is equal to other reference types, it will no longer point to module.exports, and the content in module.exports cannot be changed), the content is as follows:

console.log("** module_b开始执行 **")
let name = "I'm module_b"
console.log(name, "** 打印b的名字 **")
module.exports = {
  name
}
console.log("** module_b结束执行 **")

Run node index.js in the current directory terminal and get The following output:

*** index.js开始执行 ***
** module_a开始执行 **
** module_a结束执行 **
** module_b开始执行 **
I am module_b ** 打印b的名字 **
** module_b结束执行 **
{} '*** 打印module_a ***'
{ name: 'I am module_b' } '*** 打印module_b ***'
*** index.js结束执行 ***
I am module_a ** setTimeout打印a的名字 **

通过以上执行结果可以得出结论:

  • require某个js文件时,如果未通过exports或者module.exports指定导出内容,则require返回的结果是一个空对象;反之可以通过module.export或者给exports属性赋值来导出指定内容。

  • require某个js文件时,该文件会立即sync执行。

require导入模块

我们先选择一个npm包——cors。 进入文件夹,运行一下命令:

npm init -y // 初始化
echo -e "let cors = require(\"cors\")\nconsole.log(cors)" > index.js // 生成index.js文件
npm install cors --save // 安装cors包

文件结构如下(...处省略了其他的模块):

.
├── index.js
├── node_modules
│  ├── cors
│  │  ├── CONTRIBUTING.md
│  │  ├── HISTORY.md
│  │  ├── LICENSE
│  │  ├── README.md
│  │  ├── lib
│  │  │  └── index.js
│  │  └── package.json
│  │  ...
├── package-lock.json
└── package.json

index.js中的内容如下:

let cors = require("cors")
console.log(cors)

运行 node index.js ,得出以下结果:

[Function: middlewareWrapper]

找到node_modules下的cors模块文件夹,观察cros模块中的package.json文件,找到main字段: "main": "./lib/index.js" ,找到main字段指向的文件,发现这是一个IIFE,在IIFE中的代码中添加,console.log("hello cors"),模拟代码结构如下:

(function () {
  'use strict';
  console.log("hello cors"); // 这是手动添加的代码
  ...
  function middlewareWrapper(o) {
    ...
  }
  module.exports = middlewareWrapper;
})()

再次运行 node index.js ,得出以下结果:

hello cors
[Function: middlewareWrapper]

为什么会打印出 hello cors 呢?因为require模块的时候,引入的是该模块package.json文件中main字段指向的文件。而这个js文件会自动执行,跟require引用本地js文件是相同的。

packjson文档

在npm的官方网站中可以找到关于package.json中的main字段定义。

main   The main field is a module ID that is the primary entry point to your program. That is, if your package is named foo, and a user installs it, and then does require("foo"), then your main module's exports object will be returned.   This should be a module ID relative to the root of your package folder   For most modules, it makes the most sense to have a main script and often not much else.

在以上说明中可以得出以下结论:

  • main字段是一个模块ID,是程序的主入口。

  • 当使用require("xxx")的时候,导入的是main字段对应的js文件里的module.exports。

所以require导入模块的时候,是运行的对应模块package.json中main字段指定的文件。

推荐学习:《node视频教程

The above is the detailed content of node require what does it mean. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Frontend Development with React: Advantages and TechniquesFrontend Development with React: Advantages and TechniquesApr 17, 2025 am 12:25 AM

The advantages of React are its flexibility and efficiency, which are reflected in: 1) Component-based design improves code reusability; 2) Virtual DOM technology optimizes performance, especially when handling large amounts of data updates; 3) The rich ecosystem provides a large number of third-party libraries and tools. By understanding how React works and uses examples, you can master its core concepts and best practices to build an efficient, maintainable user interface.

React vs. Other Frameworks: Comparing and Contrasting OptionsReact vs. Other Frameworks: Comparing and Contrasting OptionsApr 17, 2025 am 12:23 AM

React is a JavaScript library for building user interfaces, suitable for large and complex applications. 1. The core of React is componentization and virtual DOM, which improves UI rendering performance. 2. Compared with Vue, React is more flexible but has a steep learning curve, which is suitable for large projects. 3. Compared with Angular, React is lighter, dependent on the community ecology, and suitable for projects that require flexibility.

Demystifying React in HTML: How It All WorksDemystifying React in HTML: How It All WorksApr 17, 2025 am 12:21 AM

React operates in HTML via virtual DOM. 1) React uses JSX syntax to write HTML-like structures. 2) Virtual DOM management UI update, efficient rendering through Diffing algorithm. 3) Use ReactDOM.render() to render the component to the real DOM. 4) Optimization and best practices include using React.memo and component splitting to improve performance and maintainability.

React in Action: Examples of Real-World ApplicationsReact in Action: Examples of Real-World ApplicationsApr 17, 2025 am 12:20 AM

React is widely used in e-commerce, social media and data visualization. 1) E-commerce platforms use React to build shopping cart components, use useState to manage state, onClick to process events, and map function to render lists. 2) Social media applications interact with the API through useEffect to display dynamic content. 3) Data visualization uses react-chartjs-2 library to render charts, and component design is easy to embed applications.

Frontend Architecture with React: Best PracticesFrontend Architecture with React: Best PracticesApr 17, 2025 am 12:10 AM

Best practices for React front-end architecture include: 1. Component design and reuse: design a single responsibility, easy to understand and test components to achieve high reuse. 2. State management: Use useState, useReducer, ContextAPI or Redux/MobX to manage state to avoid excessive complexity. 3. Performance optimization: Optimize performance through React.memo, useCallback, useMemo and other methods to find the balance point. 4. Code organization and modularity: Organize code according to functional modules to improve manageability and maintainability. 5. Testing and Quality Assurance: Testing with Jest and ReactTestingLibrary to ensure the quality and reliability of the code

React Inside HTML: Integrating JavaScript for Dynamic Web PagesReact Inside HTML: Integrating JavaScript for Dynamic Web PagesApr 16, 2025 am 12:06 AM

To integrate React into HTML, follow these steps: 1. Introduce React and ReactDOM in HTML files. 2. Define a React component. 3. Render the component into HTML elements using ReactDOM. Through these steps, static HTML pages can be transformed into dynamic, interactive experiences.

The Benefits of React: Performance, Reusability, and MoreThe Benefits of React: Performance, Reusability, and MoreApr 15, 2025 am 12:05 AM

React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

React: Creating Dynamic and Interactive User InterfacesReact: Creating Dynamic and Interactive User InterfacesApr 14, 2025 am 12:08 AM

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft