How to Remove a File in Node.js

This guide shows how to delete files in Node.js using fs.unlink and fs.promises.unlink, with examples for both synchronous and asynchronous approaches.

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.
Related

How to Get the Project Root Path in Node.js When working with large Node.js projects, you often need to find the root directory at runtime…

15 Oct, 2025

If you’re trying to run nodemon from the terminal and see the error: nodemon: command not found, it usually means the nodemon package is not…

10 Oct, 2025

Writing to files is a common task in Node.js, whether for logging, saving uploads or creating reports. Node.js has various methods through the built-in fs…

07 Oct, 2025