如何获得总目录中的文件?
如何获得总目录中的文件? 最好的办法 ?
这是一个简单的解决scheme,使用核心Nodejs fs库与asynchronous库相结合。 它是完全asynchronous的,应该像'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); } }); }
我testing了下面的代码,它工作得很好。 请让我知道,如果有什么你不明白的。
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); }); // ---下面的一切都是可选的--- size.stderr.on('data',function(data){ console.log('stderr:'+ data); }); size.on('exit',function(code){ console.log('使用代码退出的subprocess'+代码); });
礼貌链接
第二种方法:
您可能想要将Node.js API引用为child_process
使用du: https : //www.npmjs.org/package/du
require('du')('/home/rvagg/.npm/', function (err, size) { console.log('The size of /home/rvagg/.npm/ is:', size, 'bytes') })
查看node.js 文件系统function 。 看起来您可以使用fs.readdir(path, [cb])
和fs.stat(file, [cb])
来列出目录中的文件并对其大小进行求和。
像这样(完全未经testing):
var fs = require('fs'); fs.readdir('/path/to/dir', function(err, files) { var i, totalSizeBytes=0; if (err) throw err; for (i=0; i<files.length; i++) { fs.stat(files[i], function(err, stats) { if (err) { throw err; } if (stats.isFile()) { totalSizeBytes += stats.size; } }); } }); // Figure out how to wait for all callbacks to complete // eg by using a countdown latch, and yield total size // via a callback.
请注意,此解决scheme仅考虑直接存储在目标目录中的纯文件,不执行recursion。 通过检查stats.isDirectory()
和进入,虽然可能会使“等待完成”步骤复杂化,但recursion解决scheme会自然而然地出现。
ES6变体:
import path_module from 'path' import fs from 'fs' // computes a size of a filesystem folder (or a file) export function fs_size(path, callback) { fs.lstat(path, function(error, stats) { if (error) { return callback(error) } if (!stats.isDirectory()) { return callback(undefined, stats.size) } let total = stats.size fs.readdir(path, function(error, names) { if (error) { return callback(error) } let left = names.length if (left === 0) { return callback(undefined, total) } function done(size) { total += size left-- if (left === 0) { callback(undefined, total) } } for (let name of names) { fs_size(path_module.join(path, name), function(error, size) { if (error) { return callback(error) } done(size) }) } }) }) }