del、fs-extra、remove 和 rimraf 都是 Node.js 生态中用于删除文件或目录的工具,但它们的定位和维护状态截然不同。rimraf 是底层递归删除的标准实现,del 是基于 rimraf 的现代 Promise 封装,fs-extra 提供了增强版的文件系统 API(包含删除功能),而 remove 包已过时不再推荐使用。
在 Node.js 开发中,清理构建产物、重置临时目录或删除旧日志是常见需求。虽然原生 fs 模块提供了 unlink 和 rmdir,但处理递归删除和通配符匹配非常麻烦。del、fs-extra、remove 和 rimraf 试图解决这些问题,但它们的实现方式和适用场景有很大区别。
不同的包采用了不同的异步处理模式,这直接影响代码的可读性和维护成本。
del 基于 Promise 设计,天然支持 async/await,符合现代 JavaScript 标准。
// del: 原生 Promise 支持
import { deleteAsync } from 'del';
await deleteAsync(['dist/*.js', 'dist/*.css']);
// 返回已删除路径的数组
fs-extra 同时提供回调和 Promise 风格,API 与原生 fs 模块高度一致。
// fs-extra: 支持 Promise 和 Callback
import fs from 'fs-extra';
// Promise 风格
await fs.remove('dist');
// 回调风格
fs.remove('dist', err => { /*...*/ });
rimraf 早期版本主要基于回调,v5+ 版本转向 ESM 和 Promise,但底层逻辑依然保持简洁。
// rimraf: 现代版本支持 Promise
import { rimraf } from 'rimraf';
await rimraf('dist');
// 专注于递归删除,不返回复杂结果
remove 包采用老旧的回调模式,不支持 Promise,需要手动封装才能在现代代码中使用。
// remove: 仅支持回调 (已过时)
import remove from 'remove';
remove('dist', function (err) {
if (err) throw err;
console.log('deleted');
});
处理批量文件删除时,是否支持 Glob 模式(如 *.js)是关键差异点。
del 内置了 globby,直接支持通配符匹配,无需额外配置。
// del: 内置 Glob 支持
await deleteAsync(['tmp/**/*.log', '!tmp/important.log']);
// 支持排除模式,非常灵活
rimraf 支持简单的通配符,但主要设计用于删除单个路径或简单模式。
// rimraf: 基础 Glob 支持
await rimraf('tmp/*.log');
// 复杂模式可能需要配合 glob 包使用
fs-extra 本身不支持通配符,需要配合 glob 包手动实现。
// fs-extra: 需配合 glob 使用
import glob from 'glob';
import fs from 'fs-extra';
const files = await glob('tmp/*.log');
await Promise.all(files.map(f => fs.remove(f)));
remove 不支持通配符,只能删除指定路径的文件或目录。
// remove: 无 Glob 支持
remove('tmp/file.log', cb);
// 批量删除需要自己写循环
选择库时,维护状态直接关系到项目的长期安全和技术债务。
remove 包已经多年未更新,社区普遍认为它已过时。它的功能完全被 fs-extra 的 remove 方法覆盖。在新项目中引入它是一个明显的技术债务信号。
rimraf 是行业标准,被无数核心工具依赖。虽然 API 简单,但非常稳定。注意 v5 版本之后仅支持 ESM 模块。
del 保持活跃更新,专门针对前端构建场景优化。它处理了 Windows 路径锁定等边缘情况,比直接调用 rimraf 更省心。
fs-extra 是文件系统操作的瑞士军刀,维护非常积极。如果你的项目已经用它来做 copy 或 move,那么用它来做 remove 是自然的选择。
你需要在构建前清理 dist 目录,并删除所有临时日志。
del// 构建脚本示例
import { deleteAsync } from 'del';
await deleteAsync(['dist', 'tmp/*.log']);
你正在编写一个内部工具库,需要统一的文件操作 API。
fs-extra// 工具库示例
import fs from 'fs-extra';
await fs.remove('/tmp/cache');
你正在开发一个需要极致兼容性的命令行工具。
rimraf// CLI 工具示例
import { rimraf } from 'rimraf';
await rimraf(process.argv[2]);
你正在维护一个 5 年前的老项目。
remove 包,建议计划迁移到 fs-extra。| 特性 | del | fs-extra | rimraf | remove |
|---|---|---|---|---|
| 异步模式 | Promise | Promise / Callback | Promise / Callback | Callback |
| Glob 支持 | ✅ 内置 | ❌ 需配合 glob | ⚠️ 基础支持 | ❌ 无 |
| 维护状态 | 🟢 活跃 | 🟢 活跃 | 🟢 活跃 | 🔴 过时 |
| 主要用途 | 构建清理 | 通用文件操作 | 底层递归删除 | 已淘汰 |
| 模块类型 | ESM | CJS / ESM | ESM (v5+) | CJS |
del 是前端构建任务的首选 🧹 — 它解决了通配符和 Promise 的痛点,让清理代码变得非常干净。
fs-extra 是通用文件操作的最佳拍伴 🤝 — 如果你已经在使用它,就不要引入额外的删除库,保持一致性更重要。
rimraf 是底层实现的基石 🪨 — 当你需要最纯粹的递归删除功能,或者作为库的依赖时,它是最可靠的选择。
remove 包应该被移除 🗑️ — 它不再符合现代开发标准,迁移成本很低,但收益很高。
最终建议:在现代前端工程中,优先使用 del 处理构建清理,使用 fs-extra 处理应用内的文件操作。避免引入过时的 remove 包,除非你正在维护无法修改的遗留代码。
选择 fs-extra 如果你的项目已经依赖它来处理其他文件操作(如拷贝、移动)。它的 remove 方法 API 一致性好,支持同步和异步,且维护活跃。
选择 rimraf 如果你需要最底层的递归删除能力,或者在编写 CLI 工具。它是许多其他工具(包括 del)的底层依赖,兼容性极强,但 API 相对基础。
选择 del 如果你正在编写构建脚本或需要处理通配符模式(如 dist/*.js)。它基于 Promise,支持异步操作,并且默认忽略不存在的文件,非常适合现代前端工作流。
不要在新技术栈中使用 remove 包。它已多年未更新,缺乏 Promise 支持,且功能已被 fs-extra 和 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 separately:
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