First, Introduction
The Nodejs has a simple module loading system. In Nodejs, the files and modules are one by one corresponding (each file is considered a separate module), this file may be JavaScript code, JSON or compiled c/s extension, for example:
/**/function() { console.log ("Hello nodejs!" );}
/**/var foo = require ("./foo.js"); Foo.hello ();
Second, how to export the module--module.exports and exports difference
Each module in the Nodejs automatically creates a module object, and there is a property called exports under the Module object that assigns an instance of a class to module.exports to export an instance of the class. Before the module is executed, Nodejs assigns the value of Module.exports to the global variable exports so that module.exports.f = ... Can be more concise written exports.f = .... Note: Just like all variables, if you re-assign a value to exports, it is no longer bound to module.exports, nor does it export the specified module
For example:
/**/functionfunction() { console.log ("Hello Nodejs! " New Foo ();
/**/functionfunction() { console.log ("Hello Nodejs! " = Foo;
/**/function() { console.log ("Hello nodejs!" );}
Iii. mechanism of require
Assuming Y is the path, X is the file name or directory name, and when Nodejs encounters require (y+x), it is processed in the following order:
1. If X is the core module (for example: Require ("http"))
A. Return to the module
B. No further execution
2. If Y is "./", "/" or ". /"Start
A. Take x as a file, start with the specified path, and look for the following file: X, X.js, X.json, X.node, as long as one exists, returns the file and no longer executes
B. Treat X as a directory, start with the specified path, and then look for the following file: X/package.json (main field), X/index.js, X/index.json, X/index.node, returns the file if one exists, and no longer executes
3. If X is not a core module, there is no "./", "/" or ". /"begins, Nodejs will try to load the module from its/node_module directory, starting with the parent directory of the current module, and if it is not found, move to the next parent directory until the root directory of the file system
4. Throw "Not Found"
Nodejs's modular system and the mechanism of require