rimraf vs del vs fs-extra
Node.js 文件与目录删除方案对比
rimrafdelfs-extraSimilar Packages:

Node.js 文件与目录删除方案对比

del、fs-extra 和 rimraf 都是 Node.js 生态中用于删除文件和目录的常用工具,但它们的侧重点不同。del 擅长使用通配符模式批量删除文件;rimraf 专注于跨平台的递归目录删除(类似 rm -rf),对 Windows 锁文件处理较好;fs-extra 则是 fs 模块的增强版,提供了包括 remove 在内的多种文件操作方法。随着 Node.js 14.14+ 原生支持 fs.rm,这些库的使用场景变得更加具体化。

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
rimraf213,383,0305,856263 kB9a day agoBlueOak-1.0.0
del15,519,0211,34533.1 kB0a month agoMIT
fs-extra09,59459.9 kB21a month agoMIT

Node.js 文件删除方案深度对比:del vs fs-extra vs rimraf

在 Node.js 开发中,清理构建目录、删除临时文件或重置环境是常见任务。虽然 Node.js 原生提供了 fs 模块,但在处理递归删除、跨平台兼容性以及通配符匹配时,原生 API 往往不够便捷。del、fs-extra 和 rimraf 是解决这些问题的三个主流方案。本文将从架构决策的角度,深入对比它们的技术特性、适用场景及代码实现。

🗑️ 核心删除能力:路径 vs 通配符

删除操作的核心差异在于输入类型:是具体的路径,还是匹配模式。

del 原生支持通配符(glob patterns)。

  • 你可以直接传入匹配字符串,它会自动查找并删除所有匹配项。
  • 适合批量清理特定扩展名的文件。
// del: 支持通配符
import del from 'del';

// 删除 dist 目录下所有的 .js 和 .map 文件
await del(['dist/*.js', 'dist/*.map']);

rimraf 专注于具体路径的递归删除。

  • 它不支持通配符,必须传入确切的路径。
  • 如果要删除匹配的文件,需要结合 glob 库手动遍历。
// rimraf: 仅支持路径
import { rimraf } from 'rimraf';

// 只能删除整个 dist 目录,不能直接匹配文件
await rimraf('./dist');

fs-extra 同样基于路径操作。

  • 提供 remove 方法,用法类似 rimraf。
  • 也不支持通配符,需要自行配合 glob 使用。
// fs-extra: 仅支持路径
import fs from 'fs-extra';

// 删除整个目录
await fs.remove('./dist');

⚡ 同步与异步支持

在构建脚本或 CLI 工具中,有时需要同步操作以确保执行顺序。

del 主要设计为异步。

  • 早期版本支持同步,但现代版本(v7+)专注于异步 API。
  • 强制使用 await 或 .then()。
// del: 异步
await del(['dist']);

rimraf 提供完整的同步和异步 API。

  • 导出 rimraf (异步) 和 rimraf.sync (同步)。
  • 适合需要在同步流程中强制清理的场景。
// rimraf: 同步与异步
import { rimraf } from 'rimraf';

// 异步
await rimraf('./dist');
// 同步
rimraf.sync('./dist');

fs-extra 也提供完整的同步和异步 API。

  • 方法名保持一致,同步方法通常带 Sync 后缀。
  • 风格与原生 fs 模块高度一致。
// fs-extra: 同步与异步
import fs from 'fs-extra';

// 异步
await fs.remove('./dist');
// 同步
fs.removeSync('./dist');

🪟 跨平台与 Windows 兼容性

Windows 文件系统对正在使用的文件有锁定机制,这常常导致删除失败。

del 底层依赖 rimraf。

  • 继承了 rimraf 的 Windows 兼容性处理能力。
  • 但在某些极端锁定情况下,可能不如直接使用 rimraf 可控。
// del: 依赖底层实现
// 内部调用 rimraf 处理实际删除
await del(['dist']);

rimraf 是处理 Windows 锁文件的行业标准。

  • 内部实现了重试机制和权限提升逻辑。
  • 当遇到 EBUSY 或 EPERM 错误时,它会尝试强制解锁。
// rimraf: 强力删除
// 专门优化了 Windows 下的锁定文件处理
await rimraf('./dist');

fs-extra 的 remove 方法在底层也倾向于使用 rimraf 或原生 fs.rm。

  • 兼容性良好,但在极端锁定情况下,行为取决于底层实现版本。
  • 通常足够满足日常开发需求。
// fs-extra: 通用兼容
// 大多数情况下表现稳定
await fs.remove('./dist');

📦 模块系统:ESM vs CommonJS

现代项目越来越倾向于使用 ESM(ECMAScript Modules),这对包的选择有影响。

del (v7+) 仅支持 ESM。

  • 无法在纯 CommonJS 项目中直接 require。
  • 需要在 package.json 中设置 "type": "module" 或使用动态导入。
// del: ESM Only
import del from 'del';
// require('del') 会报错

rimraf (v5+) 仅支持 ESM。

  • 同样无法在旧版 CommonJS 项目中直接使用。
  • 提供了 CLI 工具,可在命令行直接调用。
// rimraf: ESM Only
import { rimraf } from 'rimraf';
// require('rimraf') 会报错

fs-extra 同时支持 ESM 和 CommonJS。

  • 兼容性最好,适合需要同时支持旧版 Node.js 或混合模块系统的项目。
  • 迁移成本最低。
// fs-extra: Dual Support
import fs from 'fs-extra'; // ESM
const fs = require('fs-extra'); // CommonJS

🛠️ Node.js 原生替代方案

从 Node.js 14.14.0 开始,原生 fs 模块支持了递归删除。

fs.rm 是现代 Node.js 的首选。

  • 无需安装第三方依赖。
  • 设置 recursive: true 和 force: true 可实现类似 rimraf 的效果。
  • 如果是新项目且 Node 版本可控,建议优先使用原生 API。
// Node.js Native: 推荐方案
import fs from 'node:fs/promises';

// 递归强制删除
await fs.rm('./dist', { recursive: true, force: true });

📊 特性对比总结

特性delfs-extrarimrafNode.js 原生
通配符支持✅ 原生支持❌ 需配合 glob❌ 需配合 glob❌ 需配合 glob
递归删除✅✅✅✅ (14.14+)
同步 API❌ (v7+)✅✅✅
模块系统ESM OnlyESM + CJSESM Only内置
Windows 优化✅ (继承)✅✅ (最强)✅ (较新)
额外依赖是是是否

💡 架构决策建议

del 适合前端构建流程中的清理任务。

  • 当你需要删除 dist/*.js 但保留 dist/index.html 时,它是唯一原生支持此功能的库。
  • 适合 Webpack、Vite 等构建插件的内部逻辑。

fs-extra 适合通用工具库或全栈项目。

  • 如果你已经在使用它进行文件复制、移动或确保目录存在,继续使用 remove 保持依赖统一。
  • 适合需要兼容 CommonJS 的老牌项目。

rimraf 适合底层工具或 CLI。

  • 当你需要最可靠的目录删除且不关心通配符时,它是标准选择。
  • 适合需要发布为 CLI 工具的场景(可直接调用 rimraf 命令)。

Node.js 原生 fs.rm 适合现代新项目。

  • 如果最低 Node 版本支持 14.14+,优先使用原生 API 减少依赖。
  • 性能最好,维护成本最低。

🎯 最终结论

这三个库没有绝对的优劣,只有场景的匹配。

  • 需要通配符删除?选 del。
  • 需要兼容旧项目或统一文件操作?选 fs-extra。
  • 需要最强力的目录删除或CLI 工具?选 rimraf。
  • 拥有现代 Node 环境?优先选 fs.rm。

在实际架构中,建议逐步向 Node.js 原生 API 迁移,仅在需要通配符或特殊兼容性时保留第三方库。

How to Choose: rimraf vs del vs fs-extra

  • rimraf:

    选择 rimraf 如果你需要最可靠的递归目录删除功能,特别是在 Windows 环境下处理被锁定的文件。它是许多其他工具底层的删除引擎,适合需要纯粹、强力删除目录的场景。

  • del:

    选择 del 如果你需要根据通配符模式(glob patterns)批量删除文件,例如清理构建产物中的特定类型文件。它内置了 glob 支持,无需额外组合其他库,适合前端构建脚本中的清理任务。

  • fs-extra:

    选择 fs-extra 如果你已经在项目中使用了它提供的其他功能(如 copy、move、ensureDir)。它的 remove 方法可以统一删除接口,且同时支持 CommonJS 和 ESM 模块系统,兼容性最好。

README for rimraf

The UNIX command rm -rf for node in a cross-platform implementation.

Install with npm install rimraf.

[!CAUTION]

Please Be Safe, this tool deletes and moves stuff, by design

The intended purpose of this tool is to remove files and directories from the filesystem, aggressively and recursively removing all items that it can find under a given target.

It goes without saying that you must not pass untrusted input to this function or CLI tool, just as you would not to the rm(1) command or the unlink(2) function. It is very challenging to guarantee that any user input will be safe to remove recursively in this way.

Furthermore, note that if you allow untrusted parties to provide arguments to the rimraf command line tool, they may also specify the --tmp=<dir> folder used by the --impl=move-remove strategy, which can move files to an arbitrary place on disk.

Because the intended purpose of this tool is the permanent destruction of filesystem entries, any security reports that rely on untrusted input being passed to the function or command line tool will be rejected.

It is your responsibility as a user to never pass untrusted user input to this module, or your system can be destroyed or compromised.

Major Changes

v5 to v6

  • Require node 20 or >=22
  • Add --version to CLI

v4 to v5

  • There is no default export anymore. Import the functions directly using, e.g., import { rimrafSync } from 'rimraf'.

v3 to v4

  • The function returns a Promise instead of taking a callback.
  • Globbing requires the --glob CLI option or glob option property to be set. (Removed in 4.0 and 4.1, opt-in support added in 4.2.)
  • Functions take arrays of paths, as well as a single path.
  • Native implementation used by default when available, except on Windows, where this implementation is faster and more reliable.
  • New implementation on Windows, falling back to "move then remove" strategy when exponential backoff for EBUSY fails to resolve the situation.
  • Simplified implementation on POSIX, since the Windows affordances are not necessary there.
  • As of 4.3, return/resolve value is boolean instead of undefined.

API

Hybrid module, load either with import or require().

// 'rimraf' export is the one you probably want, but other
// strategies exported as well.
import { rimraf, rimrafSync, native, nativeSync } from 'rimraf'
// or
const { rimraf, rimrafSync, native, nativeSync } = require('rimraf')

All removal functions return a boolean indicating that all entries were successfully removed.

The only case in which this will not return true is if something was omitted from the removal via a filter option.

rimraf(f, [opts]) -> Promise

This first parameter is a path or array of paths. The second argument is an options object.

Options:

  • preserveRoot: If set to boolean false, then allow the recursive removal of the root directory. Otherwise, this is not allowed.

  • tmp: Windows only. Temp folder to place files and folders for the "move then remove" fallback. Must be on the same physical device as the path being deleted. Defaults to os.tmpdir() when that is on the same drive letter as the path being deleted, or ${drive}:\temp if present, or ${drive}:\ if not.

  • maxRetries: Windows and Native only. Maximum number of retry attempts in case of EBUSY, EMFILE, and ENFILE errors. Default 10 for Windows implementation, 0 for Native implementation.

  • backoff: Windows only. Rate of exponential backoff for async removal in case of EBUSY, EMFILE, and ENFILE errors. Should be a number greater than 1. Default 1.2

  • maxBackoff: Windows only. Maximum total backoff time in ms to attempt asynchronous retries in case of EBUSY, EMFILE, and ENFILE errors. Default 200. With the default 1.2 backoff rate, this results in 14 retries, with the final retry being delayed 33ms.

  • retryDelay: Native only. Time to wait between retries, using linear backoff. Default 100.

  • signal Pass in an AbortSignal to cancel the directory removal. This is useful when removing large folder structures, if you'd like to limit the time spent.

    Using a signal option prevents the use of Node's built-in fs.rm because that implementation does not support abort signals.

  • glob Boolean flag to treat path as glob pattern, or an object specifying glob options.

  • filter Method that returns a boolean indicating whether that path should be deleted. With async rimraf methods, this may return a Promise that resolves to a boolean. (Since Promises are truthy, returning a Promise from a sync filter is the same as just not filtering anything.)

    The first argument to the filter is the path string. The second argument is either a Dirent or Stats object for that path. (The first path explored will be a Stats, the rest will be Dirent.)

    If a filter method is provided, it will only remove entries if the filter returns (or resolves to) a truthy value. Omitting a directory will still allow its children to be removed, unless they are also filtered out, but any parents of a filtered entry will not be removed, since the directory will not be empty in that case.

    Using a filter method prevents the use of Node's built-in fs.rm because that implementation does not support filtering.

Any other options are provided to the native Node.js fs.rm implementation when that is used.

This will attempt to choose the best implementation, based on the Node.js version and process.platform. To force a specific implementation, use one of the other functions provided.

rimraf.sync(f, [opts])
rimraf.rimrafSync(f, [opts])

Synchronous form of rimraf()

Note that, unlike many file system operations, the synchronous form will typically be significantly slower than the async form, because recursive deletion is extremely parallelizable.

rimraf.native(f, [opts])

Uses the built-in fs.rm implementation that Node.js provides. This is used by default on Node.js versions greater than or equal to 14.14.0.

rimraf.native.sync(f, [opts])
rimraf.nativeSync(f, [opts])

Synchronous form of rimraf.native

rimraf.manual(f, [opts])

Use the JavaScript implementation appropriate for your operating system.

rimraf.manual.sync(f, [opts])
rimraf.manualSync(f, opts)

Synchronous form of rimraf.manual()

rimraf.windows(f, [opts])

JavaScript implementation of file removal appropriate for Windows platforms. Works around unlink and rmdir not being atomic operations, and EPERM when deleting files with certain permission modes.

First deletes all non-directory files within the tree, and then removes all directories, which should ideally be empty by that time. When an ENOTEMPTY is raised in the second pass, falls back to the rimraf.moveRemove strategy as needed.

rimraf.windows.sync(path, [opts])
rimraf.windowsSync(path, [opts])

Synchronous form of rimraf.windows()

rimraf.moveRemove(path, [opts])

Moves all files and folders to the parent directory of path with a temporary filename prior to attempting to remove them.

Note that, in cases where the operation fails, this may leave files lying around in the parent directory with names like .file-basename.txt.0.123412341. Until the Windows kernel provides a way to perform atomic unlink and rmdir operations, this is, unfortunately, unavoidable.

To move files to a different temporary directory other than the parent, provide opts.tmp. Note that this must be on the same physical device as the folder being deleted, or else the operation will fail.

This is the slowest strategy, but most reliable on Windows platforms. Used as a last-ditch fallback by rimraf.windows().

rimraf.moveRemove.sync(path, [opts])
rimraf.moveRemoveSync(path, [opts])

Synchronous form of rimraf.moveRemove()

Command Line Interface

rimraf version 6.0.1

Usage: rimraf <path> [<path> ...]
Deletes all files and folders at "path", recursively.

Options:
  --                   Treat all subsequent arguments as paths
  -h --help            Display this usage info
  --version            Display version
  --preserve-root      Do not remove '/' recursively (default)
  --no-preserve-root   Do not treat '/' specially
  -G --no-glob         Treat arguments as literal paths, not globs (default)
  -g --glob            Treat arguments as glob patterns
  -v --verbose         Be verbose when deleting files, showing them as
                       they are removed. Not compatible with --impl=native
  -V --no-verbose      Be silent when deleting files, showing nothing as
                       they are removed (default)
  -i --interactive     Ask for confirmation before deleting anything
                       Not compatible with --impl=native
  -I --no-interactive  Do not ask for confirmation before deleting

  --impl=<type>        Specify the implementation to use:
                       rimraf: choose the best option (default)
                       native: the built-in implementation in Node.js
                       manual: the platform-specific JS implementation
                       posix: the Posix JS implementation
                       windows: the Windows JS implementation (falls back to
                                move-remove on ENOTEMPTY)
                       move-remove: a slow reliable Windows fallback

Implementation-specific options:
  --tmp=<path>        Temp file folder for 'move-remove' implementation
  --max-retries=<n>   maxRetries for 'native' and 'windows' implementations
  --retry-delay=<n>   retryDelay for 'native' implementation, default 100
  --backoff=<n>       Exponential backoff factor for retries (default: 1.2)

mkdirp

If you need to create a directory recursively, check out mkdirp.