“This article is participating in the technical topic essay node.js advanced road, click to see details”
preface
Hello everyone, I am L student. In this article, we will focus on how to pass parameters to node programs, and we will cover node global objects in detail.
There are also a number of built-in objects in Node that can help you do a lot of things, including manipulating paths, files, etc. In this article, let’s take a look at some of the built-in modules used in Node.
The path module
The path module is used to handle paths and files and provides many methods.
path.resolve
One requirement is to concatenate the path and filename.
const basePath = '/user/why'
const filename = 'abc.txt'
Copy the code
So somebody would do a concatenation using string concatenation.
const filePath = basePath + '/' + filename
console.log(filePath);
Copy the code
This result is fine, but depending on the system, Windows can use \ or \\ or/as the path separator, while Unix operating systems on Mac OS and Linux use/as the path separator.
To solve the above problems, we can usepath.resolveTo concatenate paths.
const path = require('path')
const basePath = '/user/why'
const filename = 'abc.txt'
const filePath = path.resolve(basePath, filename)
console.log(filePath);
Copy the code
Get information from the path
- Dirname: Gets the parent folder of the file
- Basename: Obtains the file name
- Extname: obtains the file extension name
const path = require('path')
const filePath = '/User/haha/abc.txt'
console.log(path.dirname(filePath));
console.log(path.basename(filePath));
console.log(path.extname(filePath));
Copy the code
Path joining together
If we want to concatenate multiple paths, but different operating systems may use different separators, we can use the path.join function.
const path = require('path')
const basepath = '/User/haha'
const filename = 'abc.txt'
const filePath = path.join(basepath, filename)
console.log(filePath);
Copy the code
Concatenate files with a folder
If we want to concatenate a file and folder, we can use path.resolve.
const basepath = 'User/haha'
const filename = 'abc.txt'
Copy the code
Path. resolve and path.join can also be used to concatenate paths.
const basepath = '.. /User/haha'
const filename = './abc.txt'
const othername = './haha.js'
const filePath1 = path.join(basepath, filename, othername)
console.log(filePath1);
const filePath2 = path.resolve(basepath, filename, othername)
console.log(filePath2);
Copy the code
We can see the difference.
Fs module
Node file system apis generally provide three modes of operation:
- Synchronize action files: the code is blocked and will not continue execution
- Asynchronous callback function operation file: the code is not blocked, the callback function needs to be passed in, and the callback function executes when the result is retrieved
- Asynchronous Promise action files: the code will not block. Calls to fs.promises will return a Promise that can be processed by then and catch.
Read file state (information)
Mode 1: fs.statsync
const fs = require('fs')
const filepath = './abc.txt'
const info = fs.statSync(filepath)
console.log('Code to execute later');
console.log(info);
Copy the code
Mode 2 Asynchronous operation
fs.stat(filepath, (err, info) = > {
if(err) {
console.log(err);
return
}
console.log(info);
console.log(info.isFile()); // Check if it is a file
console.log(info.isDirectory()); // Check if it is a folder
})
console.log('Code to execute later');
Copy the code
Method three: Promise
fs.promises.stat(filepath).then(info= > {
console.log(info);
}).catch(err= > {
console.log(err);
})
console.log('Code to execute later');
Copy the code
File descriptor
Node assigns a numeric file descriptor to all open files. All file system operations use these file descriptors to identify and track each particular file.
The fs.open() method is used to assign a new file descriptor, fd. Once assigned, a file descriptor can be used to read data from, write data to, or request information about a file.
const fs = require('fs')
fs.open('./abc.txt'.(err, fd) = > {
if(err) {
console.log(err);
return
}
// Use the file descriptor to get file information
fs.fstat(fd, (err, info) = > {
console.log(info); })})Copy the code
File reading and writing
Fs. readFile(path[, options], callback) : Reads the contents of the file
Fs. writeFile(path[, options], callback) : Writes to a file
The option parameter:
Flag: indicates the write mode
Encoding: indicates the character encoding
File writing
fs.writeFile('./abc.txt', content, {flag: "a"}, err= > {
console.log(err);
})
Copy the code
File reading
fs.readFile('./abc.txt'.(err, data) = > {
console.log(data);
})
Copy the code
If encoding is not entered, the result Buffer(binary) is returned.
fs.readFile('./abc.txt', {encoding: 'utf-8'}, (err, data) = > {
console.log(data);
})
Copy the code
Creating a folder
Use fs.mkdir() or fs.mkdirsync to create a new folder.
const fs = require('fs')
// Create a folder
const dirname = './haha'
if(! fs.existsSync(dirname)) { fs.mkdir(dirname,(err) = > {
console.log(err); })}Copy the code
Gets the contents of the folder
fs.readdir
fs.readdir(dirname, (err, files) = > {
console.log(files);
})
Copy the code
Get all the files in the folder, at this point the directory looks like the following image, you can use recursion.
const fs = require('fs')
const path = require('path')
const dirname = './haha'
function getFiles(dirname) {
fs.readdir(dirname, {withFileTypes: true}, (err, files) = > {
// console.log(files);
for(let file of files) {
// Check if it is a folder
if(file.isDirectory()) {
const filepath = path.resolve(dirname, file.name)
getFiles(filepath)
} else {
console.log(file.name);
}
}
})
}
getFiles(dirname)
Copy the code
rename
You can rename the folder using fs.rename.
fs.rename('./haha'.'./xixi'.err= > {
console.log(err);
})
Copy the code