nodejs list files in directory

Hi Guy’s Welcome to Proto Coders Point, In this article let’s check out how to list files in a folder/directory using node.js.

In Node.js, we can make use of fs module with promises (fs.promises) to asynchronously list out all the files in a directory.

Example on how to list all files in a directory using NodeJS

Below is my nodejs project structure, which has a files folder with document such a image, text files. I want to list all the files using nodeJS code.

nodejs project structure

In NodeJS fs library module, we can make use of fs.readdir() function to get list of files in defined directory.

Here is an example on How to use fs.readdir() function in nodejs

const fs = require('fs');
const path = require('path');

const directoryPath = path.join(__dirname, 'files');  // here files is my folder name.

fs.readdir(directoryPath, (err, files) => {
    if (err) {
        return console.log(`Unable to scan directory: ${err}`);
    }
    files.forEach((file) => {
        console.log(file);
    });
});

output

nodejs example to list all files contained in a directory

In above code example, ‘path.join()’ function is used to concat path of your project directory + the directory name you provide. Then fs.readdir() function takes parameter that is the ‘directoryPath’ generated and in second argument is a callback function that will list the array of the files in the directory.