← Back to Node.js Course | Chapter 5: File System | Lesson 4 of 7

Deleting

unlink removes a file and rm removes files or whole folders.

In this page:

  1. Deleting
Syntax
javascript
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

javascript
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
  1. Deleting the wrong path
  2. Using rmdir on a non-empty directory
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.