0
0
NodejsHow-ToBeginner · 3 min read

How to Use fs.rmdir in Node.js to Remove Directories

In Node.js, you use fs.rmdir to remove an empty directory asynchronously. It takes the directory path and a callback function that runs after the removal. For recursive deletion of non-empty directories, use fs.rm with the { recursive: true } option instead.
📐

Syntax

The fs.rmdir function removes an empty directory asynchronously. It requires two arguments:

  • path: The string path of the directory to remove.
  • callback: A function called after the operation finishes, with an error argument if it fails.

Note: fs.rmdir only removes empty directories. For non-empty directories, use fs.rm with recursive option.

javascript
fs.rmdir(path, callback)
💻

Example

This example shows how to remove an empty directory named test-dir. It logs success or error messages.

javascript
import fs from 'fs';

const dirPath = './test-dir';

fs.rmdir(dirPath, (err) => {
  if (err) {
    console.error('Failed to remove directory:', err.message);
  } else {
    console.log('Directory removed successfully');
  }
});
Output
Directory removed successfully
⚠️

Common Pitfalls

Common mistakes when using fs.rmdir include:

  • Trying to remove a directory that is not empty, which causes an error.
  • Not handling errors in the callback, leading to silent failures.
  • Using fs.rmdir for recursive deletion, which it does not support.

For recursive removal, use fs.rm with { recursive: true } option instead.

javascript
import fs from 'fs';

// Wrong: trying to remove non-empty directory
fs.rmdir('./non-empty-dir', (err) => {
  if (err) {
    console.error('Error:', err.message); // Will show error about directory not empty
  }
});

// Right: recursive removal
fs.rm('./non-empty-dir', { recursive: true, force: true }, (err) => {
  if (err) {
    console.error('Error:', err.message);
  } else {
    console.log('Directory and contents removed');
  }
});
Output
Error: ENOTEMPTY: directory not empty, rmdir './non-empty-dir' Directory and contents removed
📊

Quick Reference

Summary tips for using fs.rmdir:

  • Use fs.rmdir only for empty directories.
  • Always provide a callback to handle errors.
  • For deleting directories with files, use fs.rm with { recursive: true }.
  • Consider using fs.promises.rmdir for promise-based async code.

Key Takeaways

fs.rmdir removes only empty directories asynchronously with a callback.
Trying to remove non-empty directories with fs.rmdir causes errors.
Use fs.rm with { recursive: true } to delete directories with contents.
Always handle errors in the callback to avoid silent failures.
fs.promises.rmdir offers a promise-based alternative for async/await usage.