Count the number of files in a directory using JavaScript/nodejs?

Issue

How can I count the number of files in a directory using nodejs with just plain JavaScript or packages? I want to do something like this:

How to count the number of files in a directory using Python

Or in bash script I’d do this:

getLength() {
  DIRLENGTH=1
  until [ ! -d "DIR-$((DIRLENGTH+1))"  ]; do
    DIRLENGTH=$((DIRLENGTH+1))
  done
}

Solution

Using fs, I found retrieving the directory file count to be straightforward.

const fs = require('fs');
const dir = './directory';

fs.readdir(dir, (err, files) => {
  console.log(files.length);
});

Answered By – Andy Hoffman

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published