First, the definition of the module
1. In node. js, all functions are divided into modules, and a complete module loading mechanism is provided, in which case we can divide the application into various parts.
2, in the narrow sense , each JavaScript file is a module, and the multiple JavaScript files can be mutually require, they together realize a function, they are the whole external, also known as a generalized module.
3.node. js, the variables and functions defined in a JavaScript file are only valid within the file . When you need to reference these variables, functions from outside of this JS file, you must use the exports object for exposure. The user will use the Require () command to refer to this JS file.
There are two modes of cooperation between JS file and JS file:
First look at the structure of the file
1.
A JS file that provides functions for others to use. Only need to expose the function to be OK; exports.msg=msg;
Test/foo.js
var bar = require ("./bar.js"); var " Hello " ; var " hehe " ; function Showinfo () { == = Showinfo;
MSG, a variable that is scoped within a JS file.
If other people want to use this variable, then they should use exports to expose .
04.js
var foo = require ("./test/foo.js"); Console.log (foo.msg); Console.log ( Foo.info); Foo.showinfo ();
The user uses Foo to receive the exports object, which means that the Foo variable here is the exports variable in the file.
2, a certain JS file, describes a class. Module.exports = people;
People.js
function People (name,sex,age) { this. Name = name; this. Sex = sex; this. Age = { sayhello:function () { console.log this. age);} } // at this point, people is considered a constructor and can be instantiated with new. module.exports = people;
05.js
var People = require ("./test/people.js"); var New People (" Xiao Ming "," male ", "a" ); Xiaoming.sayhello ();
Iii. Catalogue of Node_modules
1, if in the Require command, so write:
1 var foo = require ("foo.js"); // not written./, so not a relative path. is a special path.
Then node. JS treats the file as a file in the Node_modules directory
2, Node_modules folder is not necessarily in the sibling directory, in any direct ancestor level directory, can be. It can even be placed in the folder of the NODE_PATH environment variable. The benefits of doing so you'll know later: when you share a project, you don't need to bring modules with them.
3. We can use folders to manage modules, such as
Then node. JS will look for the index.js in the Bar folder under the Node_modules directory to execute.
1 var bar = require ("bar"
Each module folder, recommended to write a Package.json file, the name of this file can not be changed. Node will automatically read the configuration inside. There is a main entry, which is the entry file:
{2 "name": "Kaoladebar",3 "version": "1.0.1",4 "main": "App.js" 5 } 6
Package.json file, go to the root directory of the module folder.
node. JS module for the second day