Deleting
unlink removes a file and rm removes files or whole folders.
In this page:
Syntax
fs.unlink('path', (err) => {});
fs.rmdir('directory', (err) => {});
fs.rm('directory', { recursive: true }, (err) => {});
Deleting
fs.unlink deletes one file, fs.rmdir removes an empty directory, and fs.rm with recursive and force options removes trees. Deleting cannot be undone, so check paths carefully.
Note:
rm with force ignores missing files, which makes cleanup scripts safe to re-run.
Example: Deleting
const fs = require("fs");
fs.writeFileSync("temp.txt", "bye");
fs.unlinkSync("temp.txt");
console.log("exists after unlink:", fs.existsSync("temp.txt"));
fs.mkdirSync("tree/a/b", { recursive: true });
fs.rmSync("tree", { recursive: true, force: true });
console.log("tree exists:", fs.existsSync("tree"));
// Output:
// exists after unlink: false
// tree exists: false
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Deleting the wrong path
- Using rmdir on a non-empty directory
- Forgetting recursive for folders
Chapter Summary
- unlink deletes files
- rmdir needs an empty folder
- rm supports recursive and force
- Deletion is permanent
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: