0
0
NodejsHow-ToBeginner · 3 min read

How to Use fs.unlink in Node.js to Delete Files

In Node.js, use fs.unlink(path, callback) to delete a file asynchronously. Provide the file path as a string and a callback function to handle success or errors after deletion.
📐

Syntax

The fs.unlink method deletes a file asynchronously. It takes two arguments:

  • path: A string specifying the file path to delete.
  • callback: A function called after the operation finishes, receiving an error if any occurred.
javascript
fs.unlink(path, callback)
💻

Example

This example deletes a file named example.txt. It logs a success message if the file is deleted or an error if the file does not exist or cannot be deleted.

javascript
import fs from 'fs';

const filePath = './example.txt';

fs.unlink(filePath, (err) => {
  if (err) {
    console.error('Error deleting file:', err.message);
    return;
  }
  console.log('File deleted successfully');
});
Output
File deleted successfully
⚠️

Common Pitfalls

Common mistakes when using fs.unlink include:

  • Not handling the error in the callback, which can cause silent failures.
  • Trying to delete a file that does not exist, which triggers an error.
  • Using fs.unlinkSync without try-catch, which can crash the program on error.

Always check for errors in the callback to handle issues gracefully.

javascript
import fs from 'fs';

// Wrong: No error handling
fs.unlink('./missing.txt', () => {});

// Right: Proper error handling
fs.unlink('./missing.txt', (err) => {
  if (err) {
    console.error('Failed to delete:', err.message);
    return;
  }
  console.log('Deleted successfully');
});
📊

Quick Reference

ParameterDescription
pathString path of the file to delete
callbackFunction called after deletion with an error argument if any

Key Takeaways

Use fs.unlink(path, callback) to delete files asynchronously in Node.js.
Always handle errors in the callback to avoid silent failures.
fs.unlink does not throw errors; errors come through the callback argument.
Check that the file exists before deleting to prevent errors.
For synchronous deletion, use fs.unlinkSync with try-catch for error handling.