跳到内容

在 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() 是同步版本:

const  = ('node:fs');

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

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

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 } 会忽略异常,即使文件夹不存在也不会报错。

const  = ('node:fs');

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

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