Detailed explanation of the require function in nodejs

 

Detailed explanation of the principle of the require function in nodejs

 

Example: Execute in the current script file home/project/about/index.js

require('x')

 

Analyze its lookup order:

1, if x is a built-in module (eg: require("http"))

   a. Find from the node system module

2, if x is not a built-in file

   a. First determine that the path of x may be the following paths, and find these paths in turn

/home/project/about/node_modules/x
/home/project/node_modules/x
/home/node_modules/x
/node_modules/x

   b. If x is a file, search for the following files in turn, as long as there is one of them, return the file and no longer execute.

x
x.js
x.json
x.node

    c. If x is a directory, search for the files under the directory in turn, as long as there is one of them, return the file and no longer execute.

x/package.json
x/index.js
x/index.json
x/index.node

3, if the situation is as follows:

require('/x') or require('./x') or require('../x')

First determine the absolute path where x is located.

    a. If x is a file, search for the following files in turn, as long as one of them exists, return the file and do not execute it again.

x
x.js
x.json
x.node

    b. If x is a directory, search for the files under the directory in turn, as long as there is one of them, return the file and no longer execute.

x/package.json
x/index.js
x/index.json
x/index.node

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326100457&siteId=291194637