Home >Backend Development >PHP Tutorial >Detailed explanation of Node.js module system examples
In order to allow Node files to call each other, Node.js provides a simple module system. Modules are the basic components of Node.js applications. There is a one-to-one correspondence between files and modules. So, a Node.js file is a module. This module can be json, js or a compiled C/C++ extension.
The following is a brief introduction to the module system.
Create module
The following code simply creates a module and names it main.js. Among them, ./hello means that the hello.js file in the current directory is introduced. The default suffix of Node.js is js, so there is no need to add .js.
var hello = require('./hello');hello.world();
Node.js provides two objects for use by modules, namely require and export. Export is the public interface of the module. require is used to obtain the interface of a module from the outside, that is, to obtain the export object of the module. . Next create the hello.js file.
exports.world = function() { console.log('Hello World');}
You can see that hello.js uses the export object as the interface for external access. In main.js, the module is loaded through require to directly access the member functions of the export object. To be more advanced, if we just want to encapsulate an object into a module, we can use the following method, taking 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();
Execute output in the console: HelloBYVoid
require file search strategy:
Related recommendations:
Detailed explanation of Node.js module loading
Learn Nodejs with me---Node.js module
Node.js module encapsulation and usage_node.js
The above is the detailed content of Detailed explanation of Node.js module system examples. For more information, please follow other related articles on the PHP Chinese website!