Home  >  Article  >  Web Front-end  >  node require what does it mean

node require what does it mean

藏色散人
藏色散人Original
2022-10-18 17:51:291437browse

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