To delete a file in Node.js, use fs.unlink or fs.unlinkSync. These methods offer async and sync options for file removal.
Problem
In many Node.js applications, you need to delete files dynamically. Whether it’s temp data or user uploaded content, file removal is important.
Solution
Node.js has the built-in fs (File System) module, which can be used to delete files.
Using fs.unlink() (Callback)
js
const fs = require('fs');fs.unlink('path/to/file.txt', (err) => {
if (err) {
console.error('Error deleting file:', err);
return;
}
console.log('File deleted');
});
Using fs.promises.unlink() (Promise with async/await)
js
const fs = require('fs').promises;async function deleteFile() {
try {
await fs.unlink('path/to/file.txt');
console.log('File deleted');
} catch (err) {
console.error('Error deleting file:', err);
}
}
deleteFile();
Also Read: Top Node.js IDE For Application Development
Additional Tip: Check if File Exists First
Before deleting you might want to check if the file exists to avoid exceptions:
js
const fs = require('fs');if (fs.existsSync('path/to/file.txt')) {
fs.unlinkSync('path/to/file.txt');
console.log('File removed');
} else {
console.log('File not found');
}
Conclusion
Node.js has both callback and promise-based ways to delete files using the fs module. Always handle errors properly, especially in production.