Node JS - How to Delete All Files in Directory?
Hi,
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:
If file will exists on given path then it will give you following message.
i hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Create Directory if does not Exists in Node JS?
- How to Delete File If Exists in Node JS?
- How to Get All Files from Folder in Node JS?
- How to Download Image from URL in Node JS?
- How to Create Separate Routes File in Node JS Express?
- How to Create Route in Node JS Express JS?
- Node JS Read and Write Json File Example
- How to Remove Element from Array in Node JS?
- How to use Underscore JS in Node JS App?
- Node JS Http Request with Headers Example
- Node JS Make HTTP Put Request Example