Home >Web Front-end >JS Tutorial >A brief analysis of common modules in node: path module and fs module
There are many built-in objects in node, which can help us perform many operations, including operations on paths, files, etc. The following article will introduce to you the path module and fs module among the commonly used built-in modules of node. I hope it will be helpful to you!
The path module is used to process paths and files and provides many methods.
There is a requirement to concatenate the path and file name.
const basePath = '/user/why' const filename = 'abc.txt'
Then someone will use string splicing to splice.
const filePath = basePath + '/' + filename console.log(filePath);
Although there is no problem with this result, considering different systems, Windows systems can use \ or \\ or / as path separators, while Mac OS and Linux Unix operating systems use / as path separators. symbol.
To solve the above problem, we can use path.resolve to splice paths.
const path = require('path') const basePath = '/user/why' const filename = 'abc.txt' const filePath = path.resolve(basePath, filename) console.log(filePath);
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));
If we want to splice 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);
If we want to splice a file and a folder, we can Use path.resolve.
const basepath = 'User/haha' const filename = 'abc.txt'
path.resolve and path.join can also be used to splice paths, so what is their difference?
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);
We can see the difference.
nodejs Most file system APIs provide three operating methods:
Synchronous file operation: the code will be blocked and will not continue to execute
Asynchronous callback function file operation: the code will not be blocked and a callback needs to be passed in function, when the result is obtained, the callback function executes
Asynchronous Promise operation file: the code will not be blocked. Calling method operation through fs.promises will return a Promise, which can be passed then , catch for processing.
Method 1 synchronization operation: fs.statSync
const fs = require('fs') const filepath = './abc.txt' const info = fs.statSync(filepath) console.log('后续需要执行的代码'); console.log(info);
Method 2 asynchronous operation
fs.stat(filepath, (err, info) => { if(err) { console.log(err); return } console.log(info); console.log(info.isFile()); // 判断是否是一个文件 console.log(info.isDirectory()); // 判断是否是一个文件夹 }) console.log('后续需要执行的代码');
Method 3: Promise
fs.promises.stat(filepath).then(info => { console.log(info); }).catch(err => { console.log(err); }) console.log('后续需要执行的代码');
node is allocated for all open files A file descriptor of type numeric. All file system operations use these file descriptors to identify and track each specific file.
fs.open() method is used to allocate a new file descriptor fd. Once allocated, the file descriptor can be used to read data from the file, write data to the file, or request information about the file.
const fs = require('fs') fs.open('./abc.txt', (err, fd) => { if(err) { console.log(err); return } // 通过文件描述符去获取文件信息 fs.fstat(fd, (err, info) => { console.log(info); }) })
fs.readFile(path[, options], callback): Read file content
fs.writeFile( path[, options], callback): Write content to the file
option parameters:
flag: Writing method
encoding: Character encoding
Writing of files
fs.writeFile('./abc.txt', content, {flag: "a"}, err => { console.log(err); })
Reading of files
fs.readFile('./abc.txt', (err, data) => { console.log(data); })
If encoding is not filled in, the result Buffer (binary) will be returned.
fs.readFile('./abc.txt', {encoding: 'utf-8'}, (err, data) => { console.log(data); })
Use fs.mkdir() or fs.mkdirSync Create a new folder.
const fs = require('fs') // 创建文件夹 const dirname = './haha' if(!fs.existsSync(dirname)) { fs.mkdir(dirname, (err) => { console.log(err); }) }
fs.readdir
fs.readdir(dirname, (err, files) => { console.log(files); })
Get all the files in the folder. The directory is as shown below, Recursion can be used.
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) { // 判断是否是文件夹 if(file.isDirectory()) { const filepath = path.resolve(dirname, file.name) getFiles(filepath) } else { console.log(file.name); } } }) } getFiles(dirname)
可以使用fs.rename对文件夹进行重命名。
fs.rename('./haha', './xixi', err => { console.log(err); })
更多node相关知识,请访问:nodejs 教程!
The above is the detailed content of A brief analysis of common modules in node: path module and fs module. For more information, please follow other related articles on the PHP Chinese website!