How to Delete file in node js: Complete Guide for File Removal –
You can delete a file in Node.js using the built-in “fs” (File System) module. The “fs” module provides several methods for working with the file system, including a method for deleting files.
Here’s an example of how to delete a file using the “fs” module:
const fs = require('fs');
const filePath = ‘path/to/file.txt’;
fs.unlink(filePath, (error) => {
if (error) {
console.error(`Error deleting file: ${error}`);
} else {
console.log(`Successfully deleted file: ${filePath}`);
}
});
In this example, we start by importing the “fs” module using the require
function. We then define a constant, filePath
, that represents the path to the file we want to delete.
Next, we call the fs.unlink
method and pass in the file path as the first argument. The second argument is a callback function that will be executed when the file has been deleted.