Modular Systems
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 very simple, as follows we create a ' mk.js ' file with the following code:
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:
In the example above, Hello.js uses world as the interface for the module through the exports object, loads the module through require ('./hello ') in Main.js, and then accesses the members of Hello.js objects directly in exports function.
Sometimes we just want to encapsulate an object into a module in the following format:
Module. =function(){//... }
For example:
This allows you to get the object directly:
The results of the operation are as follows:
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's modular system