feature(size) add options

This commit is contained in:
coderaiser 2014-06-23 07:37:32 -04:00
parent d92892b84c
commit f03f13f1d3
2 changed files with 64 additions and 46 deletions

View file

@ -37,7 +37,7 @@
break;
case 'size raw':
size.get(path, 'raw', callback);
size.get(path, { type: 'raw' }, callback);
break;
case 'time':

View file

@ -18,20 +18,32 @@
*/
stat = fs.lstat;
exports.get = function(dir, type, callback) {
var total = 0;
exports.get = function(dir, options, callback) {
var type, stopOnError,
total = 0;
Util.checkArgs(arguments, ['dir', 'callback']);
if (!callback)
callback = type;
function calcSize(error, size) {
if (!error)
total += size;
if (!callback) {
callback = options;
} else {
type = options.type;
stopOnError = options.stopOnError;
}
processDir(dir, calcSize, function(error) {
function calcSize(error, size) {
if (error)
if (stopOnError)
Util.exec(callback, error);
else
size = 0;
total += size;
}
processDir(dir, calcSize, {stopOnError: false}, function(error) {
var result;
if (type !== 'raw')
@ -43,19 +55,21 @@
});
};
function processDir(dir, func, callback) {
var asyncRunning = 0,
function processDir(dir, func, options, callback) {
var stopOnError = options.stopOnError,
wasError = false,
asyncRunning = 0,
fileCounter = 1,
execCallBack = function () {
if (!fileCounter && !asyncRunning)
Util.exec(callback);
callback();
},
getDirInfo = function(dir) {
stat(dir, Util.exec.with(getStat, dir));
};
getDirInfo(dir);
function getStat(dir, error, stat) {
@ -63,42 +77,46 @@
--fileCounter;
if (error) {
callback(error);
} else {
isFile = stat.isFile(),
isDir = stat.isDirectory();
if (isFile)
func(null, stat.size);
else if (isDir) {
++asyncRunning;
if (!wasError || !stopOnError) {
if (error) {
wasError = true;
func(error);
} else {
isFile = stat.isFile(),
isDir = stat.isDirectory();
fs.readdir(dir, function(error, files) {
var getInfo, dirPath, file, n, i;
asyncRunning--;
if (!error) {
n = files.length;
fileCounter += n;
for (i = 0; i < n; i++) {
file = files[i];
dirPath = path.join(dir, file);
getInfo = Util.exec.with(getDirInfo, dirPath);
process.nextTick(getInfo);
}
}
if (!n)
execCallBack();
});
if (isFile)
func(null, stat.size);
else if (isDir) {
++asyncRunning;
fs.readdir(dir, onReaddir);
}
}
execCallBack();
}
}
function onReaddir(error, files) {
var n;
asyncRunning--;
if (!error) {
n = files.length;
fileCounter += n;
files.forEach(function(file) {
var dirPath = path.join(dir, file);
process.nextTick(function() {
getDirInfo(dirPath);
});
});
}
execCallBack();
if (!n)
execCallBack();
}
}