How to Get all Files in Directory using Node.js?

Sep 23, 2022

.

Admin

How to Get all Files in Directory using Node.js?

Hi Friends,

In this article we will cover on how to implement how to get all files in directory in node.js. this example will help you get list of all files in a directory in node.js. I’m going to show you about node.js get all files in a folder recursively. let’s discuss about how to display all files in a directory using node.js. So, let's follow few step to create example of node: list files in a directory.

There are several ways to get all files in directory in nodejs. I will give you some examples of code to get all files from the folder. We will be using Node.js fs core module to get all files in the directory, we can use following fsmethods.

So, let's start following example with output:

Step 1: Install Node JS


This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:

mkdir my-app

cd my-app

npm init

Step 2: Update server.js file

server.js

//requiring path and fs modules

const path = require('path');

const fs = require('fs');

//joining path of directory

const directoryPath = path.join(__dirname, 'uploads');

//passsing directoryPath and callback function

fs.readdir(directoryPath, function (err, files) {

//handling error

if (err) {

return console.log('Unable to scan directory: ' + err);

}

//listing all files using forEach

files.forEach(function (file) {

// Do whatever you want to do with the file

console.log(file);

});

});

Output:

img1.jpg

img2.jpg

img3.jpg

img4.jpg

I hope it can help you...

#Node JS