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

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

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

Or in a bash script I would do this:

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

Ok, I have a bash-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 

It.

-2
source

Using fs , I found it easy to get the number of files in a directory.

 const fs = require('fs'); const dir = './directory'; fs.readdir(dir, (err, files) => { console.log(files.length); }); 
+40
source

An alternative solution without an external module may not be the most efficient code, but it will do the trick without an 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); }); 
+3
source

1) Download shell.js and node.js (if you don't have one)
2) Go to where you download it, and create a file there called 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 promt command in the shelljs folder (where countFiles.js) and write node countFiles "DESTINATION_FOLDER" (for example, node countFiles "C:\Users\MyUser\Desktop\testFolder" )

+2
source

Here is a simple code,

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

Source: https://habr.com/ru/post/1236214/


All Articles