The content shared with you in this article is about the Node.js module system, which has certain reference value. Friends in need can refer to it
What is a module? Modules are used to call functions between different node.js files. In other words, a js file can be a module.
1. Create module
main.js file:
var hello = require('./hello'); hello.world();
hello.js file:
exports.world = function() { console.log('Hello World'); }
require () is used to obtain the module, and exports is the external interface object of the module. In the above example, require() obtains the interface of the hello module, returns the exports object and assigns it to the hello object. The .world() method serves as the exposed interface.
We can also use the entire object as the external interface.
For example:
//hello.js function Hello() { var name; this.setName = function(thyName) { name = thyName; }; this.sayHello = function() { console.log('Hello ' + name); }; }; module.exports = Hello;//HELLO对象作为接口
Then get this interface in main.js:
//main.js var Hello = require('./hello'); hello = new Hello(); hello.setName('BYVoid'); hello.sayHello();
Related recommendations:
Initial exploration of nodeJS_node.js
Node.js module system example detailed explanation
The above is the detailed content of Node.js module system. For more information, please follow other related articles on the PHP Chinese website!