使用 JavaScript/nodejs 计算目录中的文件数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33775113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:28:25  来源:igfitidea点击:

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

javascriptnode.js

提问by Marvin Danig

How can I count the number of files in a directory using nodejswith just plain JavaScript or packages? I want to do something like this:

如何nodejs仅使用纯 JavaScript 或包来计算目录中的文件数?我想做这样的事情:

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

如何使用Python计算目录中的文件数

Or in bash script I'd do this:

或者在 bash 脚本中我会这样做:

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

回答by Andy Hoffman

Using fs, I found retrieving the directory file count to be straightforward.

使用fs,我发现检索目录文件数很简单。

const fs = require('fs');
const dir = './directory';

fs.readdir(dir, (err, files) => {
  console.log(files.length);
});

回答by DrakaSAN

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

回答by Marin Takanov

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

1) 下载 shell.js 和 node.js (如果你没有的话)
2) 去你下载它的地方并在那里创建一个名为的文件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")

3)在shelljs文件夹(countFiles.js所在的位置)中打开命令提示符并写入node countFiles "DESTINATION_FOLDER"(例如node countFiles "C:\Users\MyUser\Desktop\testFolder"

回答by Vidya Kabber

Here the simple code,

这里是简单的代码,

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

回答by Abhishek Vispute

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

回答by Marvin Danig

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

好的,我有一个类似 bash 脚本的方法:

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.

就是这样。