使用 Node.js 中的文件夹

¥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  = ('node:fs');

const  = '/Users/joe/test';

try {
  if (!.()) {
    .();
  }
} catch () {
  .();
}

读取目录内容

¥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  = ('node:fs');

const  = '/Users/joe';

.();

你可以获取完整路径:

¥You can get the full path:

fs.readdirSync(folderPath).map( => {
  return path.join(folderPath, );
});

你也可以过滤结果以仅返回文件,并排除文件夹:

¥You can also filter the results to only return the files, and exclude the folders:

const  = ('node:fs');

const  =  => {
  return .().();
};

.(folderPath)
  .( => {
    return path.join(folderPath, );
  })
  .();

重命名文件夹

¥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  = ('node:fs');

.('/Users/joe', '/Users/roger',  => {
  if () {
    .();
  }
  // done
});

fs.renameSync() 是同步版本:

¥fs.renameSync() is the synchronous version:

const  = ('node:fs');

try {
  .('/Users/joe', '/Users/roger');
} catch () {
  .();
}

fsPromises.rename() 是基于 promise 的版本:

¥fsPromises.rename() is the promise-based version:

const  = ('node:fs/promises');

async function () {
  try {
    await .('/Users/joe', '/Users/roger');
  } catch () {
    .();
  }
}
();

删除文件夹

¥Remove a folder

使用 fs.rmdir()fs.rmdirSync()fsPromises.rmdir() 删除文件夹。

¥Use fs.rmdir() or fs.rmdirSync() or fsPromises.rmdir() to remove a folder.

const  = ('node:fs');

.(dir,  => {
  if () {
    throw ;
  }

  .(`${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 } 使得如果文件夹不存在,则会忽略异常。

¥{ recursive: true, force: true } makes it so that exceptions will be ignored if the folder does not exist.

const  = ('node:fs');

.(dir, { : true, : true },  => {
  if () {
    throw ;
  }

  .(`${dir} is deleted!`);
});