nodejs count files in a folder

I've used Node.js to count files in a folder many times. The easiest way to do this is by using the Node.js fs module, which provides a readdir() method that allows you to read the contents of a directory and count the files.


const fs = require('fs');

// Get the directory path
const directoryPath = path.join(__dirname, 'files');

// Read the contents of the directory
fs.readdir(directoryPath, function (err, files) {  
  // Return the number of files
  return files.length;
});

Another way to count files in a folder is to use the glob package. The glob package provides a glob() method that can be used to get the list of files in a directory and then you can use the length property to get the total number of files in that folder.


const glob = require('glob');

// Get the directory path
const directoryPath = path.join(__dirname, 'files');

// Get the list of files in the folder
const files = glob.sync(directoryPath + '/*');

// Return the number of files
return files.length;

If you want to more accurately count the number of files and ignore hidden files, you can use a for loop with the fs.stat() method, which allows you to check the isDirectory() and isFile() properties of the file to make sure it is not a hidden file.


const fs = require('fs');

// Get the directory path
const directoryPath = path.join(__dirname, 'files');

// Read the contents of the directory
fs.readdir(directoryPath, function (err, files) {  
  let fileCount = 0;
  // Loop through each file
  for (let i = 0; i < files.length; i++) {
    // Get the file stats
    const fileStats = fs.statSync(files[i]);
    // If it is a file and not a directory
    if (fileStats.isFile() && !fileStats.isDirectory()) {
      fileCount++;
    }
  }
  // Return the number of files
  return fileCount;
});

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe