Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท fs and fs/promises

Node.js fs.rmdir() method

Reference for fs.rmdir() in Node.js: delete empty directories only, error codes such as ENOTEMPTY and ENOTDIR, the deprecated recursive option and fs.rm().

fs.rmdir(path, callback) removes a directory, but only if it is empty. It is the Node counterpart of the rmdir command and the system call of the same name. If the directory still contains anything, even a hidden file, it fails with ENOTEMPTY.

That strictness is useful when you want to clean up only what is certainly unused. To delete a folder together with its contents, use fs.rm() with { recursive: true } instead. The recursive option of rmdir itself is deprecated.

NODE
import fs from "node:fs";

fs.rmdirSync("build/tmp");   // throws if build/tmp is not empty

Try it

Node.js Empty versus non-empty

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Emptying first, or using fs.rm

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
fs.rmdir(path[, options], callback)
fs.rmdirSync(path[, options]): undefined
fsPromises.rmdir(path[, options]): Promise<undefined>
Name Description
path A string, Buffer or URL.
options.maxRetries Retries on EBUSY, EMFILE, ENFILE, ENOTEMPTY or EPERM, used with recursive. Default 0.
options.retryDelay Milliseconds between retries. Default 100.
options.recursive Deprecated. Removes the tree like fs.rm(). Prefer fs.rm().

Returns: undefined.

Errors: ENOTEMPTY (or EEXIST on some systems) if the directory has entries, ENOENT if it does not exist, ENOTDIR on Linux and macOS if the path is a file (Windows reports ENOENT), EBUSY if it is a mount point or in use, EPERM/EACCES without permission.

Usage notes

  • Empty means empty. Dotfiles count. Check with fs.readdir() if you are unsure.
  • Files need unlink. rmdir on a regular file fails; use fs.unlink() or fs.rm().
  • The recursive option prints DEP0147 and is slated for removal. Newer Node versions already reject it, so code that still passes it breaks on upgrade.
  • fs.rm() has force. It can ignore a missing path with force: true; rmdir always reports ENOENT.
  • Do not remove the current directory of your own process on Windows; it fails with EBUSY.
  • Symbolic links to folders are removed with unlink, not rmdir, because the link is not a directory.
  • Order for manual cleanup: deepest directories first.