1. Node JS Module Introduction
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.
2. Create a module
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.
Example: Note that main.js and hello.js are in the same folder in the following instances
// main.js 1. require ('./hello ') introduces the Hello.js file in the current directory (./is the current directory, and node. js is the default suffix js). var hello = require ("./hello" // 2. Using the module hello.hello ("Gaoxiong")
// Hello.js // notation 1 function (name) { console.log (name);}; // notation 2 function (name) { console.log (name);} // you can do it all.
In the terminal execution: node main.js will print Gaoxiong, do not know if you have not noticed above, in the call module method always through the Hello.hello (params); is not a function that we expose in hello.js? Wrong!!! In fact, this involves the difference between the following exposure methods
- Exports: You can only expose an object, no matter what you expose, it always returns an object that contains the information you want to expose.
- Module.exports can expose arbitrary data types
Verify:
First case
main.jsvar hello = require ("./hello"); Console.log (hello); // hello.jsexports.string = "fdfffd"' fdfffd '}
// Main.js var hello = require ("./hello"); Console.log (hello); // hello.jsmodule.exports.string = "Fdfffd"; // Console.log () results {string: ' Fdfffd '}
// Main.js var hello = require ("./hello"); Console.log (hello); // hello.jsmodule.exports = "Fdfffd"; // Conosle.log () results FDFFFD
// Main.js var hello = require ("./hello"); Console.log (hello); // hello.jsexports = "Fdfffd"// conosle.log () result = = An empty object {}
The above four conditions of the object can be drawn:
Module.exports. [Name] = [XXX] with exports. [Name] All returns an Object object with the Name property
while module.exports = [xxx] Returns the actual data type and exports = [xxx] Returns an empty object: null object that does not work
Nodejs Basics: Modular Systems