Get List of all files in a directory in Node.js

Do you need to get all files present in the directory or you want to scan a directory for files using node.js, then you’re on the correct web page because in this Nodejs How to Tutorial, we will learning How to get the list of all files in a directory in Node.js.

We will be using Node.js fs core module to get all files in the directory, we can use following fs methods.

  • fs.readdir(path, callbackFunction) – This method will read all files in the directory.You need to pass directory path as the first argument and in the second argument, you can any callback function.
  • path.join([…paths]) – This method of node.js path module, we will be using to get the path of the directory and  This will join all given path segments together.

Steps to get list of all the files in a directory in Node.js

  1. Load all the required Nodejs Packages using “require”.
  2. Get the path of the directory using path.join() method.
  3. Pass the directory path and callback function in fs.readdir(path, callbackFunction) Method.
  4. The callback function should have error handling and result handling logic.
  5. inside callback function handle the error and run forEach on the array of files list from the directory.
  6. Apply your logic for each file or all the files inside the forEach function.

Full code:

//requiring path and fs modules
var path = require('path');
var fs = require('fs');

//joining path of directory 
var directoryPath = path.join(__dirname, 'Documents');

//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); 
    });
});

 

See also  How to Update Node.JS to Latest Version (Linux, Ubuntu, OSX, Windows, Others)

for example, we will scan the directory containing following files:

nodejs fs readdir

we will run our nodejs code using node file.js and For results see below:

list files of a direcory nodejs

 

If you have any queries, please comment below and thanks for reading this tutorial.

 

1 thought on “Get List of all files in a directory in Node.js”

Leave a Comment