如何获取目录中文件的总数?

Bdf*_*dfy 11 node.js

如何获取目录中文件的总数?最好的办法 ?

log*_*yth 18

这是一个使用核心Nodejs fs库与异步库相结合的简单解决方案.它是完全异步的,应该像'du'命令一样工作.

var fs = require('fs'),
    path = require('path'),
    async = require('async');

function readSizeRecursive(item, cb) {
  fs.lstat(item, function(err, stats) {
    if (!err && stats.isDirectory()) {
      var total = stats.size;

      fs.readdir(item, function(err, list) {
        if (err) return cb(err);

        async.forEach(
          list,
          function(diritem, callback) {
            readSizeRecursive(path.join(item, diritem), function(err, size) {
              total += size;
              callback(err);
            }); 
          },  
          function(err) {
            cb(err, total);
          }   
        );  
      }); 
    }   
    else {
      cb(err);
    }   
  }); 
}   
Run Code Online (Sandbox Code Playgroud)


MT.*_*MT. 5

我测试了以下代码,它工作得很好。如果您有任何不明白的地方,请告诉我。

var util  = require('util'),
spawn = require('child_process').spawn,
size    = spawn('du', ['-sh', '/path/to/dir']);

size.stdout.on('data', function (data) {
  console.log('size: ' + data);
});


// --- Everything below is optional ---

size.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
});

size.on('exit', function (code) {
  console.log('child process exited with code ' + code);
});
Run Code Online (Sandbox Code Playgroud)

礼貌链接

第二种方法:

var util = require('util'), exec = require('child_process').exec, child;
child = exec('du -sh /path/to/dir', function(error, stdout, stderr){
    console.log('stderr: ' + stderr);
    if (error !== null){
        console.log('exec error: ' + error);
    }
});
Run Code Online (Sandbox Code Playgroud)

您可能想参考child_process的 Node.js API