Skip to content
the poor coder

nodejs count files in a folder

Poor Man
Published
Reading time
2 min read

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.

Text

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.

Text

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.

Text

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

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC