rimraf vs del vs fs-extra
文件和目录删除
rimrafdelfs-extra类似的npm包:

文件和目录删除

文件和目录删除库提供了多种方法来删除文件和目录,处理文件系统操作时提供了更高的灵活性和安全性。del 是一个基于 glob 模式的删除库,适合批量删除文件和目录。fs-extra 是对 Node.js 原生 fs 模块的扩展,提供了更多文件操作功能,包括删除。rimraf 是一个专门用于递归删除目录的库,类似于 Unix 的 rm -rf 命令,适合删除深层嵌套的目录。

npm下载趋势

3 年

GitHub Stars 排名

统计详情

npm包名称
下载量
Stars
大小
Issues
发布时间
License
rimraf117,042,2855,838262 kB81 个月前BlueOak-1.0.0
del12,739,0841,34312.7 kB176 个月前MIT
fs-extra09,62457.7 kB1212 天前MIT

功能对比: rimraf vs del vs fs-extra

删除方式

  • rimraf:

    rimraf 专注于递归删除目录,类似于 Unix 的 rm -rf 命令。它在删除深层嵌套目录时表现出色,确保删除操作的彻底性。

  • del:

    del 允许基于 glob 模式删除文件和目录,支持批量删除和排除特定文件。它提供了灵活的删除方式,适合复杂的文件结构。

  • fs-extra:

    fs-extra 提供了多种删除方法,包括删除单个文件、目录和递归删除。它的删除功能是其众多文件操作功能之一,适合需要多功能的文件操作库。

异步支持

  • rimraf:

    rimraf 主要提供异步删除方法,确保删除操作不会阻塞主线程。

  • del:

    del 完全支持异步删除,返回一个 Promise,适合现代 JavaScript 异步编程。

  • fs-extra:

    fs-extra 提供同步和异步删除方法,灵活性高,适合不同的编程风格。

依赖性

  • rimraf:

    rimraf 是一个轻量级的库,专注于递归删除,没有额外的依赖,适合需要高性能删除的场景。

  • del:

    del 依赖于 globby 进行文件匹配,适合需要复杂文件匹配和删除的场景。

  • fs-extra:

    fs-extra 是一个独立的库,扩展了 Node.js 的 fs 模块,提供了丰富的文件操作功能。

代码示例

  • rimraf:

    递归删除目录

    const rimraf = require('rimraf');
    
    // 删除目录
    rimraf('path/to/directory', (err) => {
      if (err) throw err;
      console.log('目录已删除');
    });
    
  • del:

    基于 glob 模式删除文件

    const del = require('del');
    
    // 删除所有 .tmp 文件
    await del(['**/*.tmp']);
    
    // 删除特定目录,但排除某些文件
    await del(['dist/**', '!dist/important.js']);
    
  • fs-extra:

    使用 fs-extra 删除文件和目录

    const fs = require('fs-extra');
    
    // 删除单个文件
    await fs.remove('path/to/file.txt');
    
    // 递归删除目录
    await fs.remove('path/to/directory');
    

如何选择: rimraf vs del vs fs-extra

  • rimraf:

    选择 rimraf 如果你只需要一个简单、高效的递归删除目录的工具,特别是在处理深层嵌套目录时。它是删除目录的标准解决方案,性能优越。

  • del:

    选择 del 如果你需要基于 glob 模式删除文件和目录,特别是在构建工具和任务自动化中。它支持异步操作,适合现代 JavaScript 项目。

  • fs-extra:

    选择 fs-extra 如果你需要一个功能全面的文件系统操作库,除了删除外,还提供复制、移动、创建目录等功能。适合需要多种文件操作的项目。

rimraf的README

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.