ItSolutionStuff.com

Node JS - How to Delete All Files in Directory?

By Hardik Savani • September 17, 2021
Node JS

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...

Tags: Node JS
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Create Directory if does not Exists in Node JS?

Read Now →

How to Delete File If Exists in Node JS?

Read Now →

How to Get All Files from Folder in Node JS?

Read Now →

How to Download Image from URL in Node JS?

Read Now →

How to Create Separate Routes File in Node JS Express?

Read Now →

How to Create Route in Node JS Express JS?

Read Now →

Node JS Read and Write Json File Example

Read Now →

How to Remove Element from Array in Node JS?

Read Now →

How to use Underscore JS in Node JS App?

Read Now →

Node JS Http Request with Headers Example

Read Now →

Node JS Make HTTP Put Request Example

Read Now →