How to delete a file in Node.js

Sep 14, 2023#node#javascript

To delete a file in Node.js, you can use the fs module, which provides methods for working with files and directories. The fs module is built-in, so you don’t need to install any additional packages.

There are two ways to delete a file in Node.js: asynchronously and synchronously. Asynchronous means that the operation is performed in the background and does not block the execution of other code. Synchronous means that the operation is performed immediately and blocks the execution of other code until it is finished.

  1. To delete a file asynchronously, you can use the fs.unlink() method, which takes the path of the file to delete and a callback function that is invoked when the operation is completed. The callback function receives an error object as a parameter, which you can check to handle any errors that may occur. For example:
const fs = require('fs');

// delete a file asynchronously
fs.unlink('file.txt', (err) => {
  if (err) {
    console.error(err);
  } else {
    console.log('File is deleted.');
  }
});
  1. Consider using the fs.promises API, which provides promise-based file operations. It can make your code more concise and easier to work with, especially if you’re dealing with asynchronous operations.
const fs = require('fs').promises;

async function deleteFile(filePath) {
  try {
    await fs.unlink(filePath);
    console.log(`File ${filePath} has been deleted.`);
  } catch (err) {
    console.error(err);
  }
}

deleteFile('file.txt');
  1. To delete a file synchronously, you can use the fs.unlinkSync() method, which takes the path of the file to delete as a parameter and returns nothing. If an error occurs, it will throw an exception that you can catch with a try-catch block. For example:
const fs = require('fs');

try {
  fs.unlinkSync('file.txt');
  console.log('File is deleted.');
} catch (err) {
  console.error(err);
}

Be careful when using synchronous methods, as they can block the Node.js event loop and affect the performance of your application. It is recommended to use asynchronous methods whenever possible.

How to handle the ENOENT error

The error ENOENT stands for “Error NO ENTry” or “Error NO ENTity” and it means that the file or directory you are trying to access does not exist. This can happen when you are trying to delete a file that has already been deleted, moved, or renamed, or when you are using a wrong or relative path to the file.

Always handle errors when deleting files. Use try-catch blocks or callback functions to catch and handle errors gracefully. This ensures that your application doesn’t crash due to unexpected errors during the deletion process.

const fs = require('fs');

fs.unlink('file.txt', (err) => {
  if (err) {
    // An error occurred while deleting the file
    if (err.code === 'ENOENT') {
      // The file does not exist
      console.error('The file does not exist');
    } else {
      // Some other error
      console.error(err.message);
    }
  } else {
    // The file was deleted successfully
    console.log('The file was deleted');
  }
});

Ensure that your application has the necessary permissions to delete the file. If you encounter permission-related issues, you might need to run your application with elevated privileges or change file permissions in advance.

If deleting important files, consider implementing a backup and recovery strategy. This might involve copying the file to a backup location before deletion or maintaining a log of deleted files for potential recovery.

After successfully deleting a file, make sure to release any resources associated with it, such as file handles. Use fs.close if necessary to explicitly close the file.