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:
- Replace
'/path/to/your/file.txt'
with the actual path to the file you want to remove. - The
fs.unlink
function is used to delete the specified file. It takes the file path and a callback function as arguments. - 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.
Got an article suggestion?
Let us know
Explore more
Comparing Node.js Testing Libraries
This guide presents a comparison of top 9 testing libraries for Node.js to help you decide which one to use in your next project
Guides
Job Scheduling in Node.js with Agenda
This article provides a comprehensive guide for anyone looking to implement effective task scheduling in a Node.js application
Guides
-
Comparing Node.js Testing Libraries
This guide presents a comparison of top 9 testing libraries for Node.js to help you decide which one to use in your next project
Guides -
Job Scheduling in Node.js with Agenda
This article provides a comprehensive guide for anyone looking to implement effective task scheduling in a Node.js application
Guides