How to Remove File in node.js

Better Stack Team
Updated on April 4, 2024

In Node.js, you can remove (delete) a file using the built-in fs (File System) module. The fs module provides the unlink function for this purpose. Here's an example:

 
const fs = require('fs');

const filePath = '/path/to/your/file.txt'; // Replace with the actual path to your file

// Remove the file
fs.unlink(filePath, (err) => {
  if (err) {
    console.error(`Error removing file: ${err}`);
    return;
  }

  console.log(`File ${filePath} has been successfully removed.`);
});

In this example:

  1. Replace '/path/to/your/file.txt' with the actual path to the file you want to remove.
  2. The fs.unlink function is used to delete the specified file. It takes the file path and a callback function as arguments.
  3. The callback function is called once the file has been removed. If there's an error, it will be passed to the callback.

Make sure to handle errors appropriately, as attempting to remove a non-existent file or a file in use could result in an error.

Note: Deleting files is a destructive operation, so use it with caution. Always check for errors and consider adding proper error handling based on your application's requirements.