Recursive File and Directory Remover

4.0.0 · active · verified Sun Apr 19

premove is a lightweight, cross-platform utility for Node.js that recursively removes files and directories, functioning as a programmatic `rm -rf`. It offers both `Promise`-based asynchronous (`premove`) and synchronous (`premove/sync`) APIs. The current stable version is 4.0.0. Releases are generally infrequent but address breaking changes or add features, as seen with v3.0.0's migration to named exports and v4.0.0's consistent boolean return for non-existent paths. Key differentiators include its tiny footprint (208B-260B), explicit support for both async/await and synchronous operations, and a built-in CLI. It's an alternative to `fs.rm` (or `fs.rmdir` with `recursive` option), providing a simpler, focused API for recursive deletion with safeguards against deleting critical system paths.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates asynchronous recursive deletion of files and directories using `premove`, including the `cwd` option, and shows the boolean return value for existing and non-existing paths. Also includes cleanup using the sync version.

import { premove } from 'premove';
import { resolve, join } from 'path';
import { mkdir, writeFile } from 'fs/promises';

async function runExample() {
  const baseDir = resolve(__dirname, 'temp_premove_test');
  const targetDir = join(baseDir, 'foo', 'bar');
  const targetFile = join(baseDir, 'hello.txt');

  try {
    // Setup: Create directories and a file for deletion
    await mkdir(targetDir, { recursive: true });
    await writeFile(targetFile, 'temporary content');
    console.log(`Created test directory: ${targetDir}`);
    console.log(`Created test file: ${targetFile}`);

    // Example 1: Remove a directory recursively
    let removedFoo = await premove(join(baseDir, 'foo'));
    console.log(`'${join(baseDir, 'foo')}' existed and was removed: ${removedFoo}`);

    // Example 2: Remove a file using cwd option
    let removedFile = await premove('hello.txt', { cwd: baseDir });
    console.log(`'hello.txt' in '${baseDir}' existed and was removed: ${removedFile}`);

    // Example 3: Attempt to remove a non-existent path
    let removedNonExistent = await premove(join(baseDir, 'non-existent-path'));
    console.log(`'non-existent-path' existed and was removed: ${removedNonExistent} (expected false)`);

  } catch (err) {
    console.error('Error during premove example:', err);
  } finally {
    // Clean up if baseDir still exists (e.g., if an error occurred early)
    try {
      const { premove: premoveSync } = await import('premove/sync');
      premoveSync(baseDir);
      console.log(`Cleaned up base directory: ${baseDir}`);
    } catch (cleanupErr) {
      console.warn('Failed to clean up base directory:', cleanupErr.message);
    }
  }
}

runExample();

view raw JSON →