Deleting Files with fs.unlink() and fs.rm()
You'll learn how to permanently remove files from your filesystem using Node.js's file deletion APIs.
When you need to clean up temporary files, remove old logs, or delete user-uploaded content, Node.js provides built-in methods to remove files from the filesystem. Think of it like moving a file to the trash, except it's permanent — there's no recycle bin in code.
The Traditional Method: fs.unlink()
The fs.unlink() method has been Node.js's standard way to delete files for years. It takes a file path and removes that file from the filesystem:
const fs = require('fs').promises;
async function deleteOldFile() {
try {
await fs.unlink('./temp-data.txt');
console.log('File deleted successfully');
} catch (error) {
console.error('Failed to delete:', error.message);
}
}
The name "unlink" comes from Unix systems, where deleting a file actually removes a link to the file's data on disk.
The Modern Alternative: fs.rm()
Newer versions of Node.js introduced fs.rm(), which provides more flexibility and clearer intent:
async function deleteWithOptions() {
try {
await fs.rm('./old-folder/data.json');
console.log('File removed with fs.rm()');
} catch (error) {
console.error('Removal failed:', error.message);
}
}
While fs.rm() can do everything fs.unlink() does for files, it offers additional options (like recursive directory deletion) that make it more versatile for future needs.
Which Should You Use?
For simple file deletion, both work identically. fs.unlink() is widely compatible with older Node.js versions, while fs.rm() is the modern, forward-looking choice. Both permanently delete files — there's no undo.
Key Takeaway: Use fs.unlink() or fs.rm() to permanently delete files from the filesystem; fs.rm() is the newer, more flexible API for file removal operations.