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 very common and very easy with node js’s fs NPM package. fs unlink(path, callback) can be used for asynchronous file operation and unlinkSync(path) can be used for the synchronous file operation.
In this article, We will see how to work with file system while working with NodeJS.
Delete file asynchronously using Node FS unlink() function
In the below code we will try to delete a file name 'file1.txt' which is placed at the same level where the delete code is written. Here deletion will be performed asynchronously using the unlink() method.
const fs = require('fs');
const filePath = 'file1.txt';
fs.access(filePath, error => {
if (!error) {
fs.unlink(filePath,function(error){
if(error) console.error('Error Occured:', error);
console.log('File deleted!');
});
} else {
console.error('Error Occured:', error);
}
});
Delete file synchronously using Node FS unlinkSync() function
const fs = require('fs');
const filePath = 'file1.txt';
fs.access(filePath, error => {
if (!error) {
fs.unlinkSync(filePath);
} else {
console.error('Error occured:', error);
}
});
Delete all files of a directory
We may also need to delete files recursively inside a folder. So now we will see how to delete inner files and folders recursively.
const deleteFolderRecursively = function (directory_path) {
if (fs.existsSync(directory_path)) {
fs.readdirSync(directory_path).forEach(function (file, index) {
var currentPath = path.join(directory_path, file);
if (fs.lstatSync(currentPath).isDirectory()) {
deleteFolderRecursively(currentPath);
} else {
fs.unlinkSync(currentPath); // delete file
}
});
fs.rmdirSync(directory_path); // delete folder/directories
}
};
deleteFolderRecursively('public'); // call function
Let me know your thoughts over email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.
Thank You!