remove all files in a directory node js code example
Example 1: 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()
Example 2: how to delete everything from a folder in js
const fsPromises = require('fs').promises
const directory = 'your/directory/path/here'
await fsPromises.rmdir(directory, {
recursive: true
})