【问题标题】:Count the number of files in a directory using JavaScript/nodejs?使用 JavaScript/nodejs 计算目录中的文件数?
【发布时间】:2016-02-19 21:31:24
【问题描述】:

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

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

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

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

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 绝对有可能。你有什么特别的问题吗?
  • 在审核过程中会生成可能的重复 cmets。无论当时的决定如何,它们通常有助于了解读者,因为它们填充了相关的问题列表。

标签: javascript node.js


【解决方案1】:

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

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

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

【讨论】:

  • 我已经实现了上面的,它表明上面的语法是错误的。我已经将 => 替换为 function().. 在上面执行之后,我遇到了未定义的“files.length”
  • 也许你所处的环境不支持 ES6 中引入的粗箭头语法。我可以向你保证语法是正确的,你的结果有一些错误。
  • 算子目录吗?
  • @JoãoPimentelFerreira 不,先生。
【解决方案2】:
const fs = require('fs')
const length = fs.readdirSync('/home/directory').length

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      没有外部模块的替代解决方案,可能不是最有效的代码,但可以在没有外部依赖的情况下解决问题:

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

      【讨论】:

        【解决方案5】:

        这里是简单的代码,

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

        【讨论】:

          【解决方案6】:

          好的,我有一个类似 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
          

          就是这样。

          【讨论】:

          • 嘿,这行得通。我承认这是一个 bash 思想家的神器,但它确实有效!
          【解决方案7】:
          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);
          });
          

          【讨论】:

          • 用代码添加一些描述有助于更好地理解用户的解决方案。
          猜你喜欢
          • 2010-11-10
          • 2010-10-15
          • 2011-02-07
          • 2011-10-15
          • 2019-01-16
          • 2015-06-28
          • 2021-08-25
          • 2011-12-24
          • 1970-01-01
          相关资源
          最近更新 更多