node. JS provides a simple modular system to allow node. js files to be called each other.
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 very simple, as follows we create a ' hello.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:
function () { console.log (' Hello World ');}
In the example above, Hello.js uses World as the interface for the module through the exports object, loading the module through require ('./hello ') in Main.js, and then directly accessing the Hello The member function of the exports object in. js.
Sometimes we just want to encapsulate an object into a module in the following format:
function () { // ...}
For example:
function Hello () {var name; This function (thyname) { = thyname; }; This function () { console.log (' Hello ' + name); = Hello;
This allows you to get the object directly :
var Hello = require ('./hello 'new Hello (); Hello.setname (' byvoid ‘
Where are the modules on the server?
node. js comes with a module called "http" , which we request in our code and assign the return value to a local variable.
This turns our local variables into an object that has the public methods provided by all HTTP modules.
var http = require ("http"), .... Http.createserver (...);
The file lookup policy in node. JS's require method is as follows:
"Node. js" Module system, function