In Nodejs, modules can be divided into core modules and file modules.
The core module is compiled into binary code, which can be referenced only with require notation, such as (Require (' net ')).
File module refers to a JS file, a JSON file, or a. node file. The path to add the file after referencing the file module:/.../.../xxx.js represents the absolute path,./xxx.js represents the relative path (Xxx.js under the same folder), ... /Represents the previous level of the directory. If you do not add/.../、.. /If not, the module is either a core module or is loaded from a Node_modules folder.
When loading a module, it does not indicate./. //.../, load the search path of the module. If the file in '/home/ry/projects/foo.js ' calls require (' bar.js '), node will search in the following location:
Copy Code code as follows:
/home/ry/projects/node_modules/bar.js
/home/ry/node_modules/bar.js
/home/node_modules/bar.js
/node_modules/bar.js
folder as module:
First, the Package.json file is created under the root of the folder, which identifies a main module. The contents of a Package.json may be as follows:
Copy Code code as follows:
{' name ': ' Some-library ', ' main ': './lib/some-library.js '}
If this is in a folder./some-library, then require ('./some-library ') will attempt to load./some-library/lib/ Some-library.js If there are no Package.json files in this directory, node will attempt to load index.js or Index.node files from this directory. For example, if there is no Package.json file on top, then require ('./some-library ')
will attempt to load the following file:
Copy Code code as follows:
./some-library/index.js
./some-library/index.node