This simple article demonstrates of how to delete all files in folder node js. This post will give you simple example of node.js delete all files in directory. i explained simply about node delete all files in directory. you can understand a concept of node js delete all files in folder. Let’s see bellow example node.js delete files in folder.
We will use fs npm package for delete all files from folder using node.js. fs package provide readdir() and unlinkSync() for remove all files. let’s see simple example
Step 1: Create Node App
run bellow command and create node app
mkdir my-app
cd my-app
npm init
Step 2: Create server.js file
Make sure, you have created “images” folder with some images.
server.js
const fs = require('fs');
var folder = './images/';
fs.readdir(folder, (err, files) => {
if (err) throw err;
for (const file of files) {
console.log(file + ' : File Deleted Successfully.');
fs.unlinkSync(folder+file);
}
});
now you can simply run by following command:
node server.js
Output:
file deleted successfully
50