1. Basic introduction of the module
(1) Introduction of modules
In Node, each file can be viewed as a module, and each module has its own scope and namespace
But modules do not exist in isolation, different modules need to cooperate with each other to function, so modules also have exposed interfaces
(2) Classification of modules
In Node, modules fall into three categories: core modules (also known as built-in modules), third-party modules, and custom modules
- The core moduleIs the built-in module of Node, compiled into a binary file, placed in
lib
folder - Third-party modulesUsually by
npm install
Download, placenode_modules
folder - Custom modules are written by the user and can be placed anywhere in the project
2. Module import
(1) Loading sequence
We can import a module using the require statement, which accepts a string as a module identifier. Modules are loaded in the following order:
-
If the module identifier is absolute or relative (with /,./ or.. /), will be recognized as a custom module
-
If the file suffix is not omitted, for example require(‘./ accessory.js ‘)
-
The Cannot find Module exception is thrown if the specified file is not found in the specified directory
-
If the file suffix is omitted, e.g. Require (‘./entrance’)
-
Js -> anterior. json -> anterior. node
-
If not, use the entrance as a directory and continue the search under that directory
Json -> index.js -> index.json -> index.node
-
If not, the Cannot find Module exception is thrown
-
-
-
If the module identifier is not an absolute or relative path, it will be identified as a core module or a third party module
-
If it is a core module, such as require(‘ HTTP ‘)
- Look directly for the core module and throw an exception if none is found
Cannot find module
- Look directly for the core module and throw an exception if none is found
-
If a third party module such as require(‘ Express ‘)
- First in the current directory
node_modules
Look in directory - If not, it is in the directory at the next level up
node_modules
Directory to the root directory of the file system - If not found, an exception is thrown
Cannot find module
- First in the current directory
-
As you can see, the whole process of loading a module is quite complex, but Node provides a caching mechanism to speed up the loading process
- Each module is cached the first time it is loaded, and if it needs to be loaded again, it will be read directly from the cache
- Each time a module is loaded, it is first looked up in the cache. If it is not found in the cache, it is executed in the above loading order
(2) The essence of loading
Using the require statement to load a module actually does two things at once
Module. exports () : module.exports () : module.exports () : module.exports () : module.exports () : module.exports ()
// a.js
module.exports = function(x , y) { return x + y }
console.log('a')
var subtract = require('./b.js')
var result = subtract(5.2)
console.log(result) / / 3
Copy the code
// b.js
module.exports = function(x , y) { return x - y }
console.log('b')
var add = require('./a.js')
var result = add(5.2)
console.log(result) / / 7
Copy the code
Enter the node a.js command and run the a.js file. The result is as follows (note the print order) :
// a
// b
/ / 7
/ / 3
Copy the code
There are two things to note when using the require statement:
- When faced with
require
Statement is executed firstrequire
Statement, while suspending execution of the current file - Whether the module is
require
How many times? Only once
3. Module export
(1) the module exports
Each module has a Module object, and each Module object has an exports property, which is also an object
When we need to export data, we can mount it under module.exports
- Exporting multiple members
// Use require to get object
/ / method
module.exports.number = 123
module.exports.string = 'hello'
module.exports.object = {}
module.exports.array = []
/ / method 2
module.exports = {
number: 123.string: 'hello'.object: {},
array: []}Copy the code
- Exporting individual members
module.exports = function (x, y) { // use require to get function
return x + y
}
Copy the code
(2) exports
Node provides exports as a reference to module.exports for ease of use
When we need to export multiple members, we can use the following notation:
/ / method
exports.number = 123
exports.string = 'hello'
exports.object = {}
exports.array = []
/ / method 2
exports = {
number: 123.string: 'hello'.object: {},
array: []}Copy the code
You cannot export an individual member using exports, however, because modules ultimately export module.exports
Exports references to module.exports are invalided when we reassign exports
4. The nature of modules
For a module, there are two key points: one is to have its own scope, and the other is to have an exposed interface
How does a module implement these two features? A function that executes immediately does the trick
In fact, Node will execute the function immediately on top of the code we wrote and pass in the necessary parameters when compiled
exports
: Used to export module data,module.exports
A reference torequire
: Used to import other modulesmodule
: Contains basic information about the current module__filename
: Absolute path of the current module__dirname
: Absolute path of the directory where the current module resides
(function (exports.require.module, __filename, __dirname) {
/* The code we wrote */}) ()Copy the code
The require and exports we used above were passed in at compile time, so we can print them out
/ / print
console.log(__filename)
console.log(__dirname)
console.log(exports)
console.log(module)
console.log(require)
/* * exports: * C: Users\username\Desktop\index.js * C: Users\username\Desktop * {} * Module {* id: '.', * exports: {}, * parent: null, * filename: 'C:\\Users\\username\\Desktop\\index.js', * loaded: false, * children: [], * paths: * [ 'C:\\Users\\username\\Desktop\\node_modules', * 'C:\\Users\\username\\node_modules', * 'C:\\Users\\node_modules', * 'C:\\node_modules' * ] * } * { [Function: require] * resolve: { [Function: resolve] paths: [Function: paths] }, * main: Module { * id: '.', * exports: {}, * parent: null, * filename: 'C:\\Users\\username\\Desktop\\index.js', * loaded: false, * children: [], * paths: * [ 'C:\\Users\\username\\Desktop\\node_modules', * 'C:\\Users\\username\\node_modules', * 'C:\\Users\\node_modules', * 'C:\\node_modules' * ] * }, * extensions: [Object: null prototype] { * '.js': [Function], * '.json': [Function], * '.node': [Function] * }, * cache: [Object: null prototype] { * 'C:\\Users\\username\\Desktop\\index.js': Module { * id: '.', * exports: {}, * parent: null, * filename: 'C:\\Users\\username\\Desktop\\index.js', * loaded: false, * children: [], * paths: [Array] * } * } * }Copy the code