Notes 1.
Common.js is a set of js specifications, which make up for some defects in JS. No module system 2. No standard interface 3. No standard library Each JS file is an independent module
Create two js files named 01.js and 02.js
2. Import and export modules
- Module import keyword require
// import 02.js const obj = require("./02.js"); //0 depends on 02 /* 1". /", to find a custom module. If not added, to find a built-in module. Custom modules must be added". /", core modules and third-party dependent modules do not need to be added".. /"; 4. The. Js file suffix can be omitted */Copy the code
Running at terminal
const obj = require("./02.js");
console.log(obj);
Copy the code
Node -./01 Enter {} empty object
- Module export
First: Glabal
Global. Liang = {name: liang, age: 18} // This method is the only way to define global variables, but it is rarely used because global variables are rarely consideredCopy the code
Exprots: module.exports module. Exprots {} is a global variable that can be used by all modules
let liang = "123";
module.exports.liang = liang;
Copy the code
{liang: “123”}
Exports – global. Exports is equivalent to exports because there is one step: Module. Exports = 123; module. Exports = 123; module. Exports = 123; // exports. A = 100 // exports
2. Event cycle mechanism
Event queues: macro-task: Script (all code), setTimeout/setInterval, setImmediate,.. Micro-task: Process. NextTick, then in Promise
Example Create the 03.js file
process.nextTick(() => {
console.log(1);
});
process.nextTick(() => {
console.log(2);
});
new Promise(res => {
res("12")
}).then(res => {
console.log(res);
});
setImmediate(() => {
console.log(3);
process.nextTick(() => {
console.log(4);
});
});
setImmediate(() => {
console.log(5);
process.nextTick(() => {
console.log(11);
});
});
setTimeout(() => {
console.log(7);
process.nextTick(() => {
console.log(10);
});
}, 0);
process.nextTick(() => {
console.log(8);
});
console.log(6);
Copy the code
Run Node./03 on terminal result: 6 12 8 12 7 10 3 5 4 11 analysis:
- The first step is to unscript the macro task queue and sort the macro task (setTimeout), setImmediate Mediate Micro-task (Process. nextTick), and Promise (then)
- In the second step, execute then in process.nextTick and Promise in the micro-task. After the execution, clear the Micro-Task queue. If there is another asynchrony, execute it in micro-Task. If there is no asynchrony, execute step 3
- The third step is from Macro-Task to setImmediate.