How to Delete a File in Node.js: Simple Guide
In Node.js, you can delete a file using the
fs.unlink method for callbacks or fs.promises.unlink for async/await. These methods remove the specified file from the filesystem safely.Syntax
The fs.unlink method deletes a file asynchronously using a callback. The fs.promises.unlink method returns a promise and works with async/await.
fs.unlink(path, callback):pathis the file path,callbackruns after deletion or error.await fs.promises.unlink(path): deletes file and waits for completion or throws error.
javascript
import fs from 'fs'; // Callback style fs.unlink('path/to/file.txt', (err) => { if (err) throw err; console.log('File deleted'); }); // Promise style import { promises as fsPromises } from 'fs'; async function deleteFile() { try { await fsPromises.unlink('path/to/file.txt'); console.log('File deleted'); } catch (err) { console.error('Error deleting file:', err); } }
Example
This example shows how to delete a file named example.txt using async/await with fs.promises.unlink. It handles errors if the file does not exist.
javascript
import { promises as fs } from 'fs'; async function deleteExampleFile() { const filePath = './example.txt'; try { await fs.unlink(filePath); console.log(`Deleted file: ${filePath}`); } catch (error) { if (error.code === 'ENOENT') { console.log('File does not exist, nothing to delete.'); } else { console.error('Error deleting file:', error); } } } deleteExampleFile();
Output
Deleted file: ./example.txt
Common Pitfalls
Common mistakes when deleting files in Node.js include:
- Not handling errors, which can crash your app if the file doesn't exist.
- Using synchronous methods (
fs.unlinkSync) in async code, blocking the event loop. - Forgetting to await the promise when using
fs.promises.unlink, causing unexpected behavior.
Always handle errors and prefer async methods for better performance.
javascript
import { promises as fs } from 'fs'; // Wrong: forgetting to await async function wrongDelete() { fs.unlink('file.txt'); // This starts deletion but does not wait for it console.log('This may run before file is deleted'); } // Right: awaiting the promise async function rightDelete() { await fs.unlink('file.txt'); console.log('File deleted after await'); }
Quick Reference
| Method | Description | Usage Style |
|---|---|---|
| fs.unlink(path, callback) | Deletes file asynchronously with callback | Callback |
| fs.promises.unlink(path) | Deletes file asynchronously returning a promise | Promise / async-await |
| fs.unlinkSync(path) | Deletes file synchronously (blocks event loop) | Synchronous (not recommended) |
Key Takeaways
Use fs.promises.unlink with async/await for clean, modern file deletion.
Always handle errors to avoid crashes when the file does not exist.
Avoid synchronous file deletion methods to keep your app responsive.
Remember to await promises to ensure deletion completes before continuing.
Use callback style only if you need legacy support or prefer callbacks.