To allow node files to be called each other, node. JS provides a simple modular system. Modules are a basic part of the node. JS application, and the files and modules are one by one corresponding, so, a node. js file is a module that can be a JSON, JS, or a compiled c/s extension.
The following is a brief introduction to the module system.
Create a module
The following code simply creates a module named Main.js. Where./hello means that the Hello.js file is introduced in the current directory, and node. JS has the default suffix named JS, so you don't need to add. js.
var hello = require ('./hello '); Hello.world ();
node. JS provides two objects for the module to use, respectively, require and export,export are the public interfaces of the module, require is used to obtain an interface for a module externally, that is, to get the export object of the module. The Hello.js file is created below.
Exports.world = function () { console.log (' Hello World ');}
As you can see, hello.js accesses the world as an externally accessed interface through the Export object, and then main.js the module by require to directly access the member functions of the Export object. More advanced, we just want to encapsulate an object in the module, we can use the following way, take Hello.js as an example.
function Hello () { var name; This.setname = function (thyname) { name = Thyname; }; This.sayhello = function () { console.log (' Hello ' + name);}; module.exports = Hello
Main.js:var Hello=require ('./hello '); hello=new Hello (); Hello.setname (' byvoid '); Hello.sayhello ();
Perform output on console: hellobyvoid
Require file Lookup policy: