Top Related Projects
Delete files and directories
Node.js: extra methods for the fs object like copy(), remove(), mkdirs()
:shell: Portable Unix shell commands for Node.js
glob functionality for node.js
Quick Overview
Rimraf is a Node.js module that provides a cross-platform solution for the UNIX command rm -rf
. It offers a way to recursively delete files and directories, handling various edge cases and permissions issues that can arise when deleting nested structures.
Pros
- Cross-platform compatibility (works on Windows, macOS, and Linux)
- Handles complex file and directory structures efficiently
- Provides both synchronous and asynchronous APIs
- Well-maintained and widely used in the Node.js ecosystem
Cons
- Can be dangerous if used incorrectly (potential for unintended data loss)
- May require additional configuration for certain edge cases
- Performance can be slower compared to native OS commands for simple deletions
- Limited to Node.js environments
Code Examples
- Basic usage (asynchronous):
const rimraf = require('rimraf');
rimraf('./some-directory', (error) => {
if (error) {
console.error('Error deleting directory:', error);
} else {
console.log('Directory deleted successfully');
}
});
- Using promises:
const { rimraf } = require('rimraf');
async function deleteDirectory() {
try {
await rimraf('./some-directory');
console.log('Directory deleted successfully');
} catch (error) {
console.error('Error deleting directory:', error);
}
}
deleteDirectory();
- Synchronous usage:
const { rimrafSync } = require('rimraf');
try {
rimrafSync('./some-directory');
console.log('Directory deleted successfully');
} catch (error) {
console.error('Error deleting directory:', error);
}
Getting Started
To use rimraf in your Node.js project:
-
Install the package:
npm install rimraf
-
Import and use in your code:
const { rimraf } = require('rimraf'); // Asynchronous usage rimraf('./path/to/delete', { glob: true }).then(() => { console.log('Deletion complete'); }).catch((error) => { console.error('Error:', error); }); // Synchronous usage const { rimrafSync } = require('rimraf'); rimrafSync('./path/to/delete', { glob: true });
Remember to handle errors and use with caution, especially when dealing with important data or system directories.
Competitor Comparisons
Delete files and directories
Pros of del
- Supports globbing patterns for more flexible file matching
- Provides a Promise-based API for easier async operations
- Offers additional options like
dryRun
andonProgress
for better control
Cons of del
- Larger package size due to additional dependencies
- May have slightly slower performance for simple deletion tasks
- Less battle-tested compared to rimraf's long history
Code Comparison
del:
import del from 'del';
await del(['temp/*.js', '!temp/important.js']);
rimraf:
import rimraf from 'rimraf';
rimraf('temp/*.js', (err) => {
if (err) console.error(err);
});
Key Differences
- del uses a more modern, Promise-based approach, while rimraf relies on callbacks
- del supports globbing patterns out of the box, whereas rimraf requires additional setup
- rimraf is more focused on being a cross-platform
rm -rf
implementation, while del offers more features for file deletion tasks
Use Cases
- Choose del for projects requiring advanced file matching or Promise-based workflows
- Opt for rimraf in simpler scenarios or when minimizing dependencies is crucial
Both libraries effectively handle file and directory deletion, but del provides more features at the cost of increased package size and complexity.
Node.js: extra methods for the fs object like copy(), remove(), mkdirs()
Pros of fs-extra
- Provides a comprehensive set of file system operations beyond just removal
- Offers promise-based versions of all methods for easier async handling
- Includes additional utility functions like
emptyDir
andensureDir
Cons of fs-extra
- Larger package size due to more extensive functionality
- May have a steeper learning curve for users who only need simple file removal
Code Comparison
fs-extra:
const fs = require('fs-extra')
fs.remove('/tmp/myfile', err => {
if (err) return console.error(err)
console.log('success!')
})
rimraf:
const rimraf = require('rimraf')
rimraf('/tmp/myfile', (err) => {
if (err) return console.error(err)
console.log('success!')
})
Key Differences
- fs-extra is a more comprehensive file system utility library, while rimraf focuses specifically on recursive file and directory removal
- fs-extra includes rimraf-like functionality with its
remove
method, but offers many additional features - rimraf is lighter-weight and may be preferred for projects that only need file removal capabilities
- fs-extra provides both callback and promise-based APIs, while rimraf primarily uses callbacks (though a promise version is available)
Both libraries are widely used and well-maintained, with the choice between them depending on the specific needs of a project and the desired balance between functionality and package size.
:shell: Portable Unix shell commands for Node.js
Pros of shelljs
- Provides a comprehensive set of Unix shell commands for cross-platform scripting
- Offers more functionality beyond file system operations, including process management and environment variables
- Allows for chaining commands and creating complex scripts within JavaScript
Cons of shelljs
- Larger package size and more dependencies compared to rimraf
- May be overkill for projects that only need simple file system operations
- Slightly more complex API for basic tasks like removing directories
Code Comparison
rimraf:
const rimraf = require('rimraf');
rimraf('./some-directory', (error) => {
if (error) console.error('Error:', error);
else console.log('Directory removed');
});
shelljs:
const shell = require('shelljs');
if (shell.rm('-rf', './some-directory').code !== 0) {
console.error('Error: Directory removal failed');
} else {
console.log('Directory removed');
}
Both rimraf and shelljs are popular Node.js packages for file system operations, but they serve different purposes. rimraf is focused specifically on providing a cross-platform solution for recursively removing directories, while shelljs aims to bring the power of Unix shell commands to Node.js scripts.
rimraf is lightweight and specialized, making it ideal for projects that only need directory removal functionality. shelljs, on the other hand, offers a broader range of features, making it suitable for more complex scripting tasks but potentially excessive for simpler use cases.
glob functionality for node.js
Pros of node-glob
- More versatile, allowing complex file matching patterns
- Supports asynchronous and synchronous operations
- Provides more granular control over file matching
Cons of node-glob
- More complex to use for simple file operations
- Potentially slower for basic file deletion tasks
- Requires more configuration for simple use cases
Code Comparison
node-glob:
const glob = require('glob');
glob('**/*.js', (err, files) => {
console.log(files);
});
rimraf:
const rimraf = require('rimraf');
rimraf('./directory', (err) => {
console.log('done');
});
Summary
node-glob is a powerful file matching utility that offers extensive pattern matching capabilities, while rimraf is focused on efficient directory and file removal. node-glob provides more flexibility but may be overkill for simple file operations. rimraf, on the other hand, excels at quick and straightforward file and directory deletion tasks.
node-glob is ideal for projects requiring complex file searching and matching, whereas rimraf is better suited for projects that need fast and reliable file system cleanup operations. The choice between the two depends on the specific requirements of your project and the complexity of file operations needed.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
The UNIX command rm -rf
for node
in a cross-platform implementation.
Install with npm install rimraf
.
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 orglob
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 booleanfalse
, 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 toos.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 ofEBUSY
,EMFILE
, andENFILE
errors. Default10
for Windows implementation,0
for Native implementation. -
backoff
: Windows only. Rate of exponential backoff for async removal in case ofEBUSY
,EMFILE
, andENFILE
errors. Should be a number greater than 1. Default1.2
-
maxBackoff
: Windows only. Maximum total backoff time in ms to attempt asynchronous retries in case ofEBUSY
,EMFILE
, andENFILE
errors. Default200
. With the default1.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. Default100
. -
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-infs.rm
because that implementation does not support abort signals. -
glob
Boolean flag to treat path as glob pattern, or an object specifyingglob
options. -
filter
Method that returns a boolean indicating whether that path should be deleted. With asyncrimraf
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
orStats
object for that path. (The first path explored will be aStats
, the rest will beDirent
.)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.
Top Related Projects
Delete files and directories
Node.js: extra methods for the fs object like copy(), remove(), mkdirs()
:shell: Portable Unix shell commands for Node.js
glob functionality for node.js
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot