fs remove all file .txt code example
Example: how to delete all json files in a directory nodejs
const directoryPath = path.join(__dirname, "sub_directory_if_needed");
function DeleteFiles() {
fs.readdir(directoryPath, function (err, files) {
if (err) {
return console.log('Unable to scan directory: ' + err);
}
files.forEach(function (file) {
if (file !== "package.json") {
if (file.endsWith(".json")) {
fs.unlink(`${directoryPath}/${file}`, function(err) {
if (err) throw err
console.log(file, "deleted")
})
}
}
});
});
}
DeleteFiles()