37

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
}
gariepy
  • 3,576
  • 6
  • 21
  • 34
Marvin Danig
  • 3,738
  • 6
  • 39
  • 71
  • 1
    What you tried so far? – Ziki Nov 18 '15 at 08:34
  • It's definitely possible. Do you have a particular issue / question about it? – Felix Kling Nov 18 '15 at 08:35
  • 4
    Possible duplicate of [getting all filenames in a directory with node.js](http://stackoverflow.com/questions/2727167/getting-all-filenames-in-a-directory-with-node-js) – Alexander O'Mara Nov 18 '15 at 08:36
  • Possible duplicate comments are generated as part of the review process. They're often helpful to figure readers regardless of the decision at the time because they populate the related questions list. – Flexo Nov 19 '15 at 18:55

8 Answers8

85

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

For the TS enthusiasts:

fs.readdir(dir, (err: NodeJS.ErrnoException | null, files: string[]) => {
  console.log(files.length);
});
Andy Hoffman
  • 18,436
  • 4
  • 42
  • 61
  • I had implemented the above, It shown that above syntax was wrong. And I had replaced the => to function()..After Executed above, I had faced that "files.length" of undefined – Thiru Arasu Mar 01 '18 at 17:17
  • 6
    Maybe you're in an environment which does not support the fat arrow syntax introduced in ES6. I can assure you that the syntax is correct and there is some mistake on your end. – Andy Hoffman Mar 01 '18 at 17:24
  • does it count subdirectories? – João Pimentel Ferreira Mar 09 '19 at 23:07
  • 2
    @JoãoPimentelFerreira Yes, it counts directories (except the '.' and '..'), pipes, FIFO, block devices etc. [See all the stuff if counts](https://nodejs.org/api/fs.html#class-fsdirent). You have to filter the output, usually. – Dmitry Feb 03 '22 at 14:08
  • This is nice and clean but memory usage is `O(n)`, whereas it seems like it should be possible to implement an ideal solution in `O(1)` (I'm not, however, sure how to interface with the filesystem in order to achieve this! :P) – Gershom Maes Oct 08 '22 at 23:15
  • Once writing TS code, the strict typing should be used for the sake of a cleaner code. I mean 'err' and 'files' variables – Wojciech Marciniak Mar 18 '23 at 06:42
21
const fs = require('fs')
const length = fs.readdirSync('/home/directory').length
dreamLo
  • 1,612
  • 12
  • 17
4

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")

Marin Takanov
  • 1,079
  • 3
  • 19
  • 36
3

Alternative solution without external module, maybe not the most efficient code, but will do the trick without external dependency:

var fs = require('fs');

function sortDirectory(path, files, callback, i, dir) {
    if (!i) {i = 0;}                                            //Init
    if (!dir) {dir = [];}
    if(i < files.length) {                                      //For all files
        fs.lstat(path + '\\' + files[i], function (err, stat) { //Get stats of the file
            if(err) {
                console.log(err);
            }
            if(stat.isDirectory()) {                            //Check if directory
                dir.push(files[i]);                             //If so, ad it to the list
            }
            sortDirectory(callback, i + 1, dir);                //Iterate
        });
    } else {
        callback(dir);                                          //Once all files have been tested, return
    }
}

function listDirectory(path, callback) {
    fs.readdir(path, function (err, files) {                    //List all files in the target directory
        if(err) {
            callback(err);                                      //Abort if error
        } else {
            sortDirectory(path, files, function (dir) {         //Get only directory
                callback(dir);
            });
        }
    })
}

listDirectory('C:\\My\\Test\\Directory', function (dir) {
    console.log('There is ' + dir.length + ' directories: ' + dir);
});
DrakaSAN
  • 7,673
  • 7
  • 52
  • 94
0

Okay, I got a bash script like approach for this:

const shell = require('shelljs')
const path = require('path')

module.exports.count = () => shell.exec(`cd ${path.join('path', 'to', 'folder')} || exit; ls -d -- */ | grep 'page-*' | wc -l`, { silent:true }).output

That's it.

Marvin Danig
  • 3,738
  • 6
  • 39
  • 71
0

Here the simple code,

import RNFS from 'react-native-fs';
RNFS.readDir(dirPath)
    .then((result) => {
     console.log(result.length);
});
Vidya Kabber
  • 171
  • 1
  • 16
0
const readdir = (path) => {
  return new Promise((resolve, reject) => {
    fs.readdir(path, (error, files) => {
      error ? reject(error) : resolve(files);
    });
  });
};s

readdir("---path to directory---").then((files) => {
  console.log(files.length);
});
0

I think many people look for function like this:

const countFiles = (dir: string): number =>
  fs.readdirSync(dir).reduce((acc: number, file: string) => {
    const fileDir = `${dir}/${file}`;

    if (fs.lstatSync(fileDir).isDirectory()) {
      return (acc += countFiles(fileDir));
    }

    if (fs.lstatSync(fileDir).isFile()) {
      return ++acc;
    }

    return acc;
  }, 0);

They count all files in the entire file tree.

Syki
  • 1
  • 1
  • 1