🌐 Working with folders in Node.js
Node.js 的 fs 核心模块提供了许多方便的方法,可用于操作文件夹。
🌐 The Node.js fs core module provides many handy methods you can use to work with folders.
🌐 Check if a folder exists
使用 fs.access()(以及基于 Promise 的 fsPromises.access() 对应方法)来检查文件夹是否存在,以及 Node.js 是否可以按照其权限访问它。
🌐 Use fs.access() (and its promise-based fsPromises.access() counterpart) to check if the folder exists and Node.js can access it with its permissions.
🌐 Create a new folder
使用 fs.mkdir()、fs.mkdirSync() 或 fsPromises.mkdir() 来创建一个新文件夹。
🌐 Use fs.mkdir() or fs.mkdirSync() or fsPromises.mkdir() to create a new folder.
const fs = require('node:fs');
const folderName = '/Users/joe/test';
try {
if (!fs.existsSync(folderName)) {
fs.mkdirSync(folderName);
}
} catch (err) {
console.error(err);
}🌐 Read the content of a directory
使用 fs.readdir() 或 fs.readdirSync() 或 fsPromises.readdir() 来读取目录的内容。
🌐 Use fs.readdir() or fs.readdirSync() or fsPromises.readdir() to read the contents of a directory.
这段代码读取文件夹的内容(包括文件和子文件夹),并返回它们的相对路径:
🌐 This piece of code reads the content of a folder, both files and subfolders, and returns their relative path:
const fs = require('node:fs');
const folderPath = '/Users/joe';
fs.readdirSync(folderPath);你可以获取完整路径:
🌐 You can get the full path:
fs.readdirSync(folderPath).map(fileName => {
return path.join(folderPath, fileName);
});你也可以过滤结果以仅返回文件,并排除文件夹:
🌐 You can also filter the results to only return the files, and exclude the folders:
const fs = require('node:fs');
const isFile = fileName => {
return fs.lstatSync(fileName).isFile();
};
fs.readdirSync(folderPath)
.map(fileName => {
return path.join(folderPath, fileName);
})
.filter(isFile);🌐 Rename a folder
使用 fs.rename()、fs.renameSync() 或 fsPromises.rename() 来重命名文件夹。第一个参数是当前路径,第二个参数是新路径:
🌐 Use fs.rename() or fs.renameSync() or fsPromises.rename() to rename folder. The first parameter is the current path, the second the new path:
const fs = require('node:fs');
fs.rename('/Users/joe', '/Users/roger', err => {
if (err) {
console.error(err);
}
// done
});fs.renameSync() 是同步版本:
const fs = require('node:fs');
try {
fs.renameSync('/Users/joe', '/Users/roger');
} catch (err) {
console.error(err);
}fsPromises.rename() 是基于 Promise 的版本:
const fs = require('node:fs/promises');
async function example() {
try {
await fs.rename('/Users/joe', '/Users/roger');
} catch (err) {
console.log(err);
}
}
example();🌐 Remove a folder
使用 fs.rmdir()、fs.rmdirSync() 或 fsPromises.rmdir() 删除文件夹。
🌐 Use fs.rmdir() or fs.rmdirSync() or fsPromises.rmdir() to remove a folder.
const fs = require('node:fs');
fs.rmdir(dir, err => {
if (err) {
throw err;
}
console.log(`${dir} is deleted!`);
});要删除包含内容的文件夹,请使用 fs.rm(),并设置选项 { recursive: true } 以递归删除内容。
🌐 To remove a folder that has contents use fs.rm() with the option { recursive: true } to recursively remove the contents.
{ recursive: true, force: true } 会忽略异常,即使文件夹不存在也不会报错。
const fs = require('node:fs');
fs.rm(dir, { recursive: true, force: true }, err => {
if (err) {
throw err;
}
console.log(`${dir} is deleted!`);
});