refactor(size) processDir: callback -> emitter

This commit is contained in:
coderaiser 2014-11-19 05:56:00 -05:00
parent 9e5a44231d
commit 0d2c2cb99f

View file

@ -10,6 +10,8 @@
format = require(DIR + 'format'),
Util = require(DIR + 'util'),
EventEmitter= require('events').EventEmitter,
/* The lstat() function shall be equivalent to stat(),
except when path refers to a symbolic link. In that case lstat()
shall return information about the link, while stat() shall return
@ -19,22 +21,28 @@
exports.get = function(dir, options, callback) {
var type, stopOnError,
emitter = new EventEmitter(),
total = 0;
Util.check(arguments, ['dir', 'callback']);
if (!callback) {
callback = options;
options = {};
} else {
type = options.type;
stopOnError = options.stopOnError;
}
function calcSize(size) {
emitter.on('size', function(size) {
total += size || 0;
}
});
processDir(dir, calcSize, options, function(error) {
emitter.on('error', function(error) {
callback(error);
});
emitter.on('end', function() {
var result;
if (type !== 'raw')
@ -42,11 +50,13 @@
else
result = total;
callback(error, result);
callback(null, result);
});
processDir(dir, options, emitter);
};
function processDir(dir, func, options, callback) {
function processDir(dir, options, emitter) {
var stopOnError = options.stopOnError,
wasError = false,
asyncRunning = 0,
@ -57,7 +67,7 @@
yesAllDone = !fileCounter && !asyncRunning;
if (yesAllDone && noErrors)
callback();
emitter.emit('end');
},
getDirInfo = function(dir) {
@ -75,13 +85,13 @@
if (error) {
if (stopOnError) {
wasError = true;
callback(error);
emitter.emmit('error', error);
}
} else {
isDir = stat.isDirectory();
if (!isDir)
func(stat.size);
emitter.emit('size', stat.size);
else if (isDir) {
++asyncRunning;