40

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
}
4
  • 1
    What you tried so far? Commented Nov 18, 2015 at 8:34
  • It's definitely possible. Do you have a particular issue / question about it? Commented Nov 18, 2015 at 8:35
  • 4
    Possible duplicate of getting all filenames in a directory with node.js Commented Nov 18, 2015 at 8: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. Commented Nov 19, 2015 at 18:55

8 Answers 8

89

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);
});
Sign up to request clarification or add additional context in comments.

8 Comments

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
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.
does it count subdirectories?
@JoãoPimentelFerreira Yes, it counts directories (except the '.' and '..'), pipes, FIFO, block devices etc. See all the stuff if counts. You have to filter the output, usually.
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)
|
26
const fs = require('fs')
const length = fs.readdirSync('/home/directory').length

Comments

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

Comments

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

Comments

2

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.

Comments

0

Here the simple code,

import RNFS from 'react-native-fs';
RNFS.readDir(dirPath)
    .then((result) => {
     console.log(result.length);
});

Comments

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.

2 Comments

Hey, this works. It's an artifact of a bash thinker I admit, but it works!
This works but it's a terrible answer. Return a string, silent errors, useless cd and grep, only works on linux, require a external library, terrible performance...
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);
});

1 Comment

Adding some description with code helps better understand the solution to user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.