Node JS – How to Delete All Files in Directory?

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

Also Read:

Leave a Reply

Your email address will not be published. Required fields are marked *

Share this article:

RSS2k
Follow by Email0
Facebook780
Twitter3k
120
29k
130k
error

Please spread the word :)