How to Delete Files in Node JS
While working with any technology, We need to interact with a file system by creating a new file, adding content, and deleting it. With NodeJS working with file systtem is also veritably common and veritably easy with knot js’s fs NPM package. fs sever( path, message) can be used for asynchronous file operation and unlinkSync( path) can be used for the coetaneous file operation.
In this composition, We'll see how to work with file system while working with NodeJS.
delete file asynchronously using knot FS unlink() function
In the below law we will try to delete a file name'file1.txt' which is placed at the same position where the delete law is written. Then omission will be performed asynchronously using the unlink() system.
const fs = require('fs');
const file_path = 'file1.txt';
fs.access(file_path, error => {
if (!error) {
fs.unlink(file_path,function(error){
if(error) console.error('Error Occured:', error);
console.log('File Deleted Successfully!');
});
} else {
console.error('Error Occured:', error);
}
});
delete file synchronously using knot FS unlinkSync() function
const fs = require('fs');
const file_path = 'file1.txt';
fs.access(file_path, error => {
if (!error) {
fs.unlinkSync(file_path);
} else {
console.error('Error occured:', error);
}
});
delete all lines of a directory
We may also need to delete lines recursively inside a brochure. So now we will see how to delete inner lines and flyers recursively.
const delete_folder_recursively = function (directory_path) {
if (fs.existsSync(directory_path)) {
fs.readdirSync(directory_path).forEach(function (file, index) {
var current_path = path.join(directory_path, file);
if (fs.lstatSync(current_path).isDirectory()) {
delete_folder_recursively(current_path);
} else {
fs.unlinkSync(current_path);
}
});
fs.rmdirSync(directory_path);
}
};
delete_folder_recursively('public');
Thank You!