Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 } 
like image 202
Marvin Danig Avatar asked Nov 18 '15 08:11

Marvin Danig


People also ask

How do we get the count of number of files in a directory?

Browse to the folder containing the files you want to count. Highlight one of the files in that folder and press the keyboard shortcut Ctrl + A to highlight all files and folders in that folder. In the Explorer status bar, you'll see how many files and folders are highlighted, as shown in the picture below.

What is FS readdirSync?

The fs. readdirSync() method is used to synchronously read the contents of a given directory.

How can I quickly count files in a folder?

Use File Explorer Open the folder and select all the subfolders or files either manually or by pressing CTRL+A shortcut. If you choose manually, you can select and omit particular files. You can now see the total count near the left bottom of the window.


1 Answers

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); }); 
like image 161
Andy Hoffman Avatar answered Oct 21 '22 11:10

Andy Hoffman