Node. JS Module System
node. JS provides a simple modular system to allow node. js files to be called each other.
Modules are a basic part of the node. JS application, and the files and modules are one by one corresponding. In other words, a node. js file is a module that may be JavaScript code, JSON, or compiled C/s extensions.
Create a module
In node. js, creating a module is as simple as creating a main.js file with the following code:
var hello = require ('./hello '); Hello.world ();
In the above example, the code require ('./hello ') introduces the Hello.js file in the current directory (./is the current directory, and node. js is the default suffix js).
node. JS provides exports and require two objects, where exports is the interface that the module exposes, and require is used to obtain an interface from the outside of a module, the exports object of the acquired module.
Next we'll create the Hello.js file with the following code:
Exports.world = function () { console.log (' Hello World ');}
To encapsulate an object in a module:
Hello.js function Hello () { var name; This.setname = function (thyname) { name = Thyname; }; This.sayhello = function () { console.log (' Hello ' + name);}; module.exports = Hello;
This allows you to get to the object directly:
The only change to the module interface is to use Module.exports = Hello instead of Exports.world = function () {}. When the module is referenced externally, its interface object is the Hello object itself to be exported, not the original exports.
node. js comes with a module called http , which we request in our code and assign the return value to a local variable.
Loading from the file module cache
Although the native module has a different priority than the file module, it takes precedence to load the existing module from the cache of the file module.
Load from native module
The priority level of the native module is second only to the priority of the file module cache. The Require method first checks whether the module is in the list of native modules after parsing the file name. In the case of HTTP modules, although there is a Http/http.js/http.node/http.json file in the directory, require ("http") is not loaded from these files, but is loaded from the native module.
The native module also has a buffer, which is also preferentially loaded from the buffer. If the buffer has not been loaded, then the loading mode of the native module is called to load and execute.
Load from File
When the file module cache does not exist and is not a native module, node. js resolves the parameters passed in by the Require method and loads the actual file from the file system.
Excerpt from: http://www.runoob.com/nodejs/nodejs-module-system.html
Node. JS Module System