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.

Summarize with AI

Not enough time? get the key points instantly.

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();

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’);

}

Also Read:

Conclusion

Node.js has both callback and promise-based ways to delete files using the fs module. Always handle errors properly, especially in production.


Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

NodeJS

Which Company Is Best for Hiring Node.js Developers in the UK?

Node.js helps businesses build backend systems, REST APIs, real-time applications, and SaaS platforms using JavaScript. Developing these solutions requires professionals who understand application architecture, technical…

NodeJS

How to tell if Node.js is installed or not?

To verify Node.js installation, run node -v or node --version. This checks if Node.js is installed and working correctly. Problem Before you run any Node.js…