1. Core Module
Node provides many server-level APIs for js, and most of these APIs are packaged in a named core module. For example: fs core module for file operation, http module constructed by http service, path operation module, os operating system information module, etc. All passed
require('fs');
Use after introduction.
2. Module system
-
In Node, there are three types of modules
- Named core module, for example: fs, path
- User-defined module
- The relative path introduced must be added ./, cannot be omitted, otherwise an error will be reported
- The suffix name can be omitted, and the js file is accessed by default
- Third-party module
-
Scope
- There is no global scope in Node, only module scope
- The outside can't access the inside
- The inside can't access the outside
- Closed by default
- Communication between modules is achieved through require return values
-
require()
-
Role: load the module, in order to execute the code in the module and use its members
-
Return value: the interface object exported by the load file module
-
Each file module provides an object: the exports object, which is used to communicate with external modules, and use the external data that needs to be accessed by mounting on the exports object.
-
exports is an empty object by default
// a.js exports.num = 1;// 导出变量num // b.js var ex = require('./a');// 接收到处接口对象ex console.log(ex.num);// 使用对象上挂载的数据
-
Note:
- The data mounted on exports can also be used through exports on the loaded module.
-