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

1) Download shell.js and node.js (if you don't have it)
2) Go where you download it and create there a file named countFiles.js

var sh = require('shelljs');

var count = 0;
function annotateFolder (folderPath) {
  sh.cd(folderPath);
  var files = sh.ls() || [];

  for (var i=0; i<files.length; i++) {
    var file = files[i];

    if (!file.match(/.*\..*/)) {
      annotateFolder(file);
      sh.cd('../');
    } else {
      count++;
    }
  }
}
if (process.argv.slice(2)[0])
  annotateFolder(process.argv.slice(2)[0]);
else {
  console.log('There is no folder');
}

console.log(count);

3) Open the command promt in the shelljs folder (where countFiles.js is) and write node countFiles "DESTINATION_FOLDER" (e.g. node countFiles "C:\Users\MyUser\Desktop\testFolder")


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

const fs = require('fs')
const length = fs.readdirSync('/home/directory').length