In nodejs, modules can be divided into core modules and file modules.
The core module is compiled into binary code. You only need the require identifier When referencing it, for example (require ('net ')).
The file module refers to a js file, a json file, or a. node file. When referencing the file module, add the file path :/... /... /xxx. js indicates the absolute path ,. /xxx. js indicates the relative path (xxx in the same folder. js ),.. /indicates the upper-level directory. If neither/.../or.../is added, the module is either a core module or loaded from a node_modules folder.
When the module is loaded, the search path of the module is not specified. If the file in '/home/ry/projects/foo. js' calls require ('bar. js'), node will search at the following position:
Copy codeThe Code is 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 a module:
First, create the package. json file under the root of the folder, which identifies a main module. The content in a package. json may be as follows:
Copy codeThe Code is as follows:
{"Name": "some-library", "main": "./lib/some-library.js "}
If this is in a folder. /some-library, then require ('. /some-library ') will try to load. /some-library/lib/some-library.js if there is no package under this directory. json file, node will try to load index from this directory. js or index. node file. For example, if no package. json file exists,Will try to load the following file:
Copy codeThe Code is as follows:
./Some-library/index. js
./Some-library/index. node