I. Global module
Definition: Access anytime, anywhere, no reference required.
Process. env returns information about the environment variable in which the project is running. Process. argv argument array (can receive arguments passed in when executing node by command), parameter 1: returns the current node path, parameter 2: returns the current file path
Example (index.js) :
let num1 = parseInt(process.argv[2]);
let num2 = parseInt(process.argv[3]);
console.log(num1 + num2);
Copy the code
Enter the command:
node index 2 3
Copy the code
Output:
5
Copy the code
System module
Definition: Requires the require() reference, but does not require a download (it was built in when node was installed). Path: Utility for handling file paths and directory paths.
let path = require('path')
p = '/node/a/1.jpg'
path.dirname(p) // Path (/node/a)
path.basename(p) // File name (1.jpg)
path.extname(p) // File extension (.jpg)
Copy the code
Fs: used for file read and write operations.
let fs = require('fs')
fs.readFile('./a.text'.(err,data) = > {
if(err) {
console.log(err)
} else {
console.log(data.toString())
}
})
// Add content to the file
fs.writeFile('a.txt'.'test', { flag: 'a' }, (err) = > {
if (err) {
throw err
}
})
Copy the code
3. Custom modules
Definition: require encapsulates its own module.
1, the require
1) If there is a path, go to the path;
const mod1 = require('./mod')
Copy the code
2) If not, go to node_modules;
const mod1 = require('mod')
Copy the code
3) If none exists, go to the Node installation directory.
Exports and Modules
1) value
exports.a = 1;
exports.b = 2;
let c = 3;
Copy the code
Use:
mod1.a mod1.b
Copy the code
2) object
module.exports = { a:1.b:2 }
Copy the code
Use:
mod1.a mod1.b
Copy the code
3) function
module.exports = function() {}Copy the code
Use:
mod1()
Copy the code
4) class
module.exports = class {
constructor(name) { this.name = name }
show() { console.log(this.name) }
}
Copy the code
Use:
let p = new mod1('myname');
p.show()
Copy the code
4. HTTP module (key)
The template string ‘(the key to the left of the number 1) to recognize ${}.
let http = require('http')
let fs = require('fs')
http.createServer((request, response) = > { // Create an HTTP service
fs.readFile(`. /${request.url}`.(err, data) = > { // Read file (path, callback)
if (err) {
response.writeHead(404) //200 is the default
response.end('404 not found')}else {
response.end(data)
}
})
}).listen(8088)// To create a server, you must use a listening port
Copy the code