这些库旨在增强或封装 Node.js 原生的 fs 模块,解决递归创建目录、安全删除文件、处理文件描述符限制等常见痛点。fs-extra 提供了一站式的文件操作扩展,mkdirp 和 rimraf 专注于目录创建与删除,graceful-fs 用于处理并发错误,而 node-fs 则是已过时的遗留包。在现代开发中,理解它们的适用边界对于构建稳定的构建工具或后端服务至关重要。
在 Node.js 开发中,处理文件系统是构建工具、脚本和后端服务的核心需求。虽然原生 fs 模块提供了基础能力,但在实际工程中,我们常遇到递归创建目录、安全删除文件、处理并发限制等棘手问题。本文将深入对比五个常见的 npm 包,帮助你做出正确的架构决策。
创建多级目录是常见需求。原生 Node.js 在旧版本中不支持递归创建,这催生了 mkdirp 的流行。现在虽然原生支持了,但理解差异仍有必要。
mkdirp 是专门用于递归创建目录的库,兼容性好。
// mkdirp: 专门用于递归创建
const mkdirp = require('mkdirp');
await mkdirp('/tmp/foo/bar/baz');
// 即使父目录不存在,也会一路创建出来
fs-extra 封装了 mkdirp 的功能,提供了 ensureDir 方法,语义更清晰。
// fs-extra: 确保目录存在,不存在则创建
const fse = require('fs-extra');
await fse.ensureDir('/tmp/foo/bar/baz');
// 如果目录已存在,不会报错,直接返回
node-fs 曾经试图提供类似功能,但它是过时的封装。
// node-fs: 已废弃,不推荐使用
const fs = require('node-fs');
fs.mkdir('/tmp/foo/bar/baz', function(err){
// 旧式回调风格,且不再维护
});
graceful-fs 不直接提供创建目录的新 API,它是对原生 fs 的补丁。
// graceful-fs: 补丁原生 fs,包含 mkdir
const fs = require('graceful-fs');
// 使用原生 API 但具备容错能力
fs.mkdir('/tmp/foo', { recursive: true }, (err) => {});
rimraf 专注于删除,不用于创建目录。
// rimraf: 无创建目录功能,仅用于删除
// 此处仅作示意,实际不应使用 rimraf 创建目录
删除整个目录树(类似 rm -rf)在清理构建产物时非常常见。Windows 上的文件锁定问题常导致原生删除失败。
rimraf 是该领域的标准工具,处理文件锁定和权限问题非常老道。
// rimraf: 强力删除目录树
const rimraf = require('rimraf');
rimraf('/tmp/foo/bar', (err) => {
// 即使文件被占用,也会尝试重试删除
});
fs-extra 提供了 remove 方法,底层通常依赖 rimraf 或类似逻辑。
// fs-extra: 统一的删除接口
const fse = require('fs-extra');
await fse.remove('/tmp/foo/bar');
// 支持 Promise,用法简洁
mkdirp 仅用于创建,不提供删除功能。
// mkdirp: 无删除功能
// 尝试使用 mkdirp 删除文件会导致错误
graceful-fs 增强原生 fs.unlink 或 fs.rm 的稳定性,但不改变 API。
// graceful-fs: 增强原生删除的稳定性
const fs = require('graceful-fs');
fs.rm('/tmp/foo/bar', { recursive: true }, (err) => {
// 遇到 EMFILE 错误时会自动重试
});
node-fs 的删除功能已过时,且缺乏对现代边缘情况的处理。
// node-fs: 废弃的删除方法
const fs = require('node-fs');
fs.unlink('/tmp/file', (err) => {
// 不支持递归删除,需手动遍历,极易出错
});
当脚本同时打开大量文件时,容易触发 EMFILE: too many open files 错误。这是操作系统级别的限制。
graceful-fs 的核心价值就在于此。它全局修补 fs 模块,自动排队文件打开请求。
// graceful-fs: 自动处理并发限制
const fs = require('graceful-fs');
// 无需修改业务代码,直接替换 require 即可
fs.readFile('/tmp/large-file.txt', (err, data) => {
// 如果文件描述符耗尽,它会等待而不是直接报错
});
fs-extra 默认依赖 graceful-fs,因此继承了这个能力。
// fs-extra: 内置 graceful-fs 支持
const fse = require('fs-extra');
// 同样具备高并发下的稳定性
await fse.readFile('/tmp/large-file.txt');
mkdirp、rimraf 和 node-fs 本身不直接解决并发限制,除非它们内部依赖了 graceful-fs。
// mkdirp/rimraf: 依赖外部稳定性
// 建议在使用它们前先 require('graceful-fs') 进行全局补丁
const fs = require('graceful-fs');
const rimraf = require('rimraf');
node-fs 是一个历史遗留包。在 Node.js 早期,原生 fs 功能不完善,社区创建了许多补丁包。如今,原生 fs 已经非常强大。
path.exists)已合并到原生 fs 中。// ❌ 错误示范:使用 node-fs
const fs = require('node-fs'); // 不要这样做
// ✅ 正确示范:使用原生或 fs-extra
const fs = require('fs');
const fse = require('fs-extra');
| 特性 | fs-extra | graceful-fs | mkdirp | rimraf | node-fs |
|---|---|---|---|---|---|
| 核心用途 | 全能文件操作增强 | 并发稳定性补丁 | 递归创建目录 | 递归删除目录 | ❌ 已废弃 |
| Promise 支持 | ✅ 原生支持 | ❌ 需配合 util.promisify | ✅ 支持 | ✅ 支持 | ❌ 仅回调 |
| 递归创建 | ✅ ensureDir | ❌ 需原生配合 | ✅ 核心功能 | ❌ 不支持 | ⚠️ 有限支持 |
| 递归删除 | ✅ remove | ❌ 需原生配合 | ❌ 不支持 | ✅ 核心功能 | ❌ 不支持 |
| 并发保护 | ✅ 内置 | ✅ 核心功能 | ❌ 无 | ❌ 无 | ❌ 无 |
| 推荐指数 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ | 🚫 禁用 |
在现代 Node.js 项目中,fs-extra 通常是最佳起点。它几乎涵盖了 mkdirp 和 rimraf 的功能,并且默认集成了 graceful-fs 的稳定性。如果你的项目对依赖体积极其敏感,或者只需要单一功能(如只删除文件),那么单独引入 rimraf 或原生 fs 配合 graceful-fs 是更轻量级的选择。
最重要的是,彻底从依赖列表中移除 node-fs。它属于上一个时代的产物,继续使用它就像在现代汽车上使用化油器一样 — — 不仅没必要,还会带来麻烦。对于新项目,优先利用 Node.js 原生能力,仅在必要时引入经过时间考验的工具库。
选择 fs-extra 如果你需要一个能直接替换原生 fs 模块的增强版库。它内置了 copy、move 和 ensureDir 等实用方法,非常适合处理复杂的文件流转逻辑,能显著减少样板代码。
选择 graceful-fs 如果你的应用在高并发下频繁读写文件,遇到了 EMFILE 错误。它通过排队机制平滑处理文件描述符耗尽的问题,通常作为底层依赖被其他库自动使用。
选择 mkdirp 如果你只需要递归创建目录,并且需要兼容非常旧的 Node.js 版本(低于 10.12.0)。对于新项目,原生 fs.mkdir 的 recursive 选项通常是更好的选择。
不要选择 node-fs。这是一个早已停止维护的包,其功能完全被原生 fs 模块覆盖。在新项目中使用它只会增加不必要的依赖风险,应直接忽略。
选择 rimraf 如果你需要可靠地删除整个目录树,特别是在 Windows 系统上处理被锁定的文件时。虽然原生 fs.rm 已支持递归删除,但 rimraf 在边缘情况下的处理依然更加稳健。
fs-extra adds file system methods that aren't included in the native fs module and adds promise support to the fs methods. It also uses graceful-fs to prevent EMFILE errors. It should be a drop in replacement for fs.
I got tired of including mkdirp, rimraf, and ncp in most of my projects.
npm install fs-extra
fs-extra is a drop in replacement for native fs. All methods in fs are attached to fs-extra. All fs methods return promises if the callback isn't passed.
You don't ever need to include the original fs module again:
const fs = require('fs') // this is no longer necessary
you can now do this:
const fs = require('fs-extra')
or if you prefer to make it clear that you're using fs-extra and not fs, you may want
to name your fs variable fse like so:
const fse = require('fs-extra')
you can also keep both, but it's redundant:
const fs = require('fs')
const fse = require('fs-extra')
NOTE: The deprecated constants fs.F_OK, fs.R_OK, fs.W_OK, & fs.X_OK are not exported on Node.js v24.0.0+; please use their fs.constants equivalents.
There is also an fs-extra/esm import, that supports both default and named exports. However, note that fs methods are not included in fs-extra/esm; you still need to import fs and/or fs/promises seperately:
import { readFileSync } from 'fs'
import { readFile } from 'fs/promises'
import { outputFile, outputFileSync } from 'fs-extra/esm'
Default exports are supported:
import fs from 'fs'
import fse from 'fs-extra/esm'
// fse.readFileSync is not a function; must use fs.readFileSync
but you probably want to just use regular fs-extra instead of fs-extra/esm for default exports:
import fs from 'fs-extra'
// both fs and fs-extra methods are defined
Most methods are async by default. All async methods will return a promise if the callback isn't passed.
Sync methods on the other hand will throw if an error occurs.
Also Async/Await will throw an error if one occurs.
Example:
const fs = require('fs-extra')
// Async with promises:
fs.copy('/tmp/myfile', '/tmp/mynewfile')
.then(() => console.log('success!'))
.catch(err => console.error(err))
// Async with callbacks:
fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
if (err) return console.error(err)
console.log('success!')
})
// Sync:
try {
fs.copySync('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
// Async/Await:
async function copyFiles () {
try {
await fs.copy('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
}
copyFiles()
NOTE: You can still use the native Node.js methods. They are promisified and copied over to fs-extra. See notes on fs.read(), fs.write(), & fs.writev()
walk() and walkSync()?They were removed from fs-extra in v2.0.0. If you need the functionality, walk and walkSync are available as separate packages, klaw and klaw-sync.
fse-cli allows you to run fs-extra from a console or from npm scripts.
If you like TypeScript, you can use fs-extra with it: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fs-extra
If you want to watch for changes to files or directories, then you should use chokidar.
fs-filesystem allows you to read the state of the filesystem of the host on which it is run. It returns information about both the devices and the partitions (volumes) of the system.
Wanna hack on fs-extra? Great! Your help is needed! fs-extra is one of the most depended upon Node.js packages. This project
uses JavaScript Standard Style - if the name or style choices bother you,
you're gonna have to get over it :) If standard is good enough for npm, it's good enough for fs-extra.
What's needed?
Note: If you make any big changes, you should definitely file an issue for discussion first.
fs-extra contains hundreds of tests.
npm run lint: runs the linter (standard)npm run unit: runs the unit testsnpm run unit-esm: runs tests for fs-extra/esm exportsnpm test: runs the linter and all testsWhen running unit tests, set the environment variable CROSS_DEVICE_PATH to the absolute path of an empty directory on another device (like a thumb drive) to enable cross-device move tests.
If you run the tests on the Windows and receive a lot of symbolic link EPERM permission errors, it's
because on Windows you need elevated privilege to create symbolic links. You can add this to your Windows's
account by following the instructions here: http://superuser.com/questions/104845/permission-to-make-symbolic-links-in-windows-7
However, I didn't have much luck doing this.
Since I develop on Mac OS X, I use VMWare Fusion for Windows testing. I create a shared folder that I map to a drive on Windows.
I open the Node.js command prompt and run as Administrator. I then map the network drive running the following command:
net use z: "\\vmware-host\Shared Folders"
I can then navigate to my fs-extra directory and run the tests.
I put a lot of thought into the naming of these functions. Inspired by @coolaj86's request. So he deserves much of the credit for raising the issue. See discussion(s) here:
First, I believe that in as many cases as possible, the Node.js naming schemes should be chosen. However, there are problems with the Node.js own naming schemes.
For example, fs.readFile() and fs.readdir(): the F is capitalized in File and the d is not capitalized in dir. Perhaps a bit pedantic, but they should still be consistent. Also, Node.js has chosen a lot of POSIX naming schemes, which I believe is great. See: fs.mkdir(), fs.rmdir(), fs.chown(), etc.
We have a dilemma though. How do you consistently name methods that perform the following POSIX commands: cp, cp -r, mkdir -p, and rm -rf?
My perspective: when in doubt, err on the side of simplicity. A directory is just a hierarchical grouping of directories and files. Consider that for a moment. So when you want to copy it or remove it, in most cases you'll want to copy or remove all of its contents. When you want to create a directory, if the directory that it's suppose to be contained in does not exist, then in most cases you'll want to create that too.
So, if you want to remove a file or a directory regardless of whether it has contents, just call fs.remove(path). If you want to copy a file or a directory whether it has contents, just call fs.copy(source, destination). If you want to create a directory regardless of whether its parent directories exist, just call fs.mkdirs(path) or fs.mkdirp(path).
fs-extra wouldn't be possible without using the modules from the following authors:
Licensed under MIT
Copyright (c) 2011-2024 JP Richardson