Skip to main content
This recipe migrates from the deprecated fs.rmdir() method (with recursive option) to the modern fs.rm() method for removing directories.

Deprecation

Node.js deprecated fs.rmdir() and its variants when used with the recursive option. Use fs.rm() instead. See DEP0147 for more details.

Usage

Run this codemod with:
npx codemod nodejs/rmdir

Before/After

Callback API

  // Using fs.rmdir with the recursive option
- fs.rmdir(path, { recursive: true }, callback);
+ // Using fs.rm with recursive and force options
+ fs.rm(path, { recursive: true, force: true }, callback);

Synchronous API

  // Using fs.rmdirSync with the recursive option
- fs.rmdirSync(path, { recursive: true });
+ // Using fs.rmSync with recursive and force options
+ fs.rmSync(path, { recursive: true, force: true });

Promise API

  // Using fs.promises.rmdir with the recursive option
- fs.promises.rmdir(path, { recursive: true });
+ // Using fs.promises.rm with recursive and force options
+ fs.promises.rm(path, { recursive: true, force: true });

What It Does

  • Replaces fs.rmdir() with fs.rm() when recursive: true is used
  • Replaces fs.rmdirSync() with fs.rmSync() when recursive: true is used
  • Replaces fs.promises.rmdir() with fs.promises.rm() when recursive: true is used
  • Adds force: true option for safer directory removal
  • Works with all three APIs: callback, synchronous, and promise-based

Why force: true?

The force: true option ensures that errors are ignored if the path doesn’t exist, making the operation more robust and matching the behavior of the deprecated rmdir with recursive: true.

Complete Example

  const fs = require('node:fs');
  const path = require('node:path');

  const tempDir = path.join(__dirname, 'temp');

  // Callback style
- fs.rmdir(tempDir, { recursive: true }, (err) => {
+ fs.rm(tempDir, { recursive: true, force: true }, (err) => {
    if (err) throw err;
    console.log('Directory removed');
  });

  // Sync style
  try {
-   fs.rmdirSync(tempDir, { recursive: true });
+   fs.rmSync(tempDir, { recursive: true, force: true });
    console.log('Directory removed');
  } catch (err) {
    console.error(err);
  }

  // Promise style
- await fs.promises.rmdir(tempDir, { recursive: true });
+ await fs.promises.rm(tempDir, { recursive: true, force: true });
  console.log('Directory removed');
The fs.rm() method is more powerful and should be used with caution. Always verify the path before calling fs.rm() with recursive: true to avoid accidentally deleting important files.
For simple directory removal without contents, you can still use fs.rmdir() without the recursive option. The deprecation only applies when recursive: true is specified.

Build docs developers (and LLMs) love