What is the difference between fs.unlink() and fs.rmdir() (or the newer fs.rm()) in Node.js?
Short answer
fs.unlink() deletes a single file. fs.rmdir() deletes a directory, but by default only if it's empty (throwing an error otherwise).
Advertisement
AModel answer
fs.unlink() deletes a single file. fs.rmdir() deletes a directory, but by default only if it's empty (throwing an error otherwise). The newer, more flexible fs.rm() can delete both files and directories, and with the 'recursive' option set, can delete a non-empty directory and all of its contents in one call, which used to require manually walking the tree and deleting each file before removing the directory itself.
await fs.promises.unlink('file.txt'); // deletes a single file
await fs.promises.rm('temp-folder', { recursive: true, force: true }); // deletes a folder and everything in itReal-world example
A build script cleans up a previous build's output directory using fs.rm() with { recursive: true, force: true }, replacing what used to require several lines of manual recursive-deletion logic with older APIs.
Likely follow-ups
- Why does fs.rmdir() with the recursive option now emit a deprecation warning in favor of fs.rm()?
- What does the 'force' option specifically do, given 'recursive' alone handles non-empty directories?
Related topics