rimraf: Cross-Platform `rm -rf`

6.1.3 · active · verified Sun Apr 19

rimraf is a robust, cross-platform Node.js module that provides functionality akin to the `rm -rf` UNIX command for deep, recursive file and directory deletion. Currently at version 6.1.3, it is actively maintained with periodic major releases introducing significant changes, such as the shift from callbacks to Promises and the move away from default exports. A key differentiator is its specialized handling of common file system issues on Windows, such as `EBUSY` or `EMFILE` errors, through strategies like "move then remove" and exponential backoff, making it more reliable than simple native `fs.rm` alternatives in certain scenarios. It offers both synchronous and asynchronous APIs, as well as options to select native or JavaScript-based implementations. A critical aspect of its usage is the explicit warning against passing untrusted input due to its aggressive deletion capabilities, which can lead to system destruction or compromise if misused.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic asynchronous usage of `rimraf` to create a temporary directory and file, then recursively delete the directory, verifying its removal.

import { rimraf } from 'rimraf';
import { mkdir, writeFile, stat } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';

async function exampleUsage() {
  const tempDirPath = join(tmpdir(), `rimraf-example-${Date.now()}`);
  const tempFilePath = join(tempDirPath, 'test-file.txt');

  console.log(`Creating temporary directory: ${tempDirPath}`);
  await mkdir(tempDirPath, { recursive: true });
  await writeFile(tempFilePath, 'Hello, rimraf!');
  console.log(`Created temporary file: ${tempFilePath}`);

  try {
    const stats = await stat(tempDirPath);
    console.log(`Directory exists before deletion: ${stats.isDirectory()}`);
  } catch (err) {
    console.error(`Error checking directory before deletion: ${err}`);
  }

  console.log(`Attempting to delete: ${tempDirPath}`);
  // The 'rimraf' function returns a boolean indicating successful removal
  const success = await rimraf(tempDirPath);

  if (success) {
    console.log(`Successfully deleted: ${tempDirPath}`);
    try {
      await stat(tempDirPath);
      console.error('ERROR: Directory still exists after deletion!');
    } catch (err: any) {
      if (err.code === 'ENOENT') {
        console.log('Directory no longer exists (as expected).');
      } else {
        console.error(`Error checking directory after deletion: ${err}`);
      }
    }
  } else {
    console.error(`Failed to delete: ${tempDirPath}. (A filter might have prevented full removal.)`);
  }
}

exampleUsage().catch(console.error);

view raw JSON →