From 950dd5651a9e9b6d4c03e326982da54640cc7fb4 Mon Sep 17 00:00:00 2001 From: coderaiser Date: Mon, 23 Jun 2014 06:23:35 -0400 Subject: [PATCH] refactor(size) get --- lib/server/size.js | 54 +++++++++++++++++++++++++--------------------- 1 file changed, 30 insertions(+), 24 deletions(-) diff --git a/lib/server/size.js b/lib/server/size.js index 42f77a01..f8076eee 100644 --- a/lib/server/size.js +++ b/lib/server/size.js @@ -26,10 +26,9 @@ if (!callback) callback = type; - function calcSize(stat) { - var size = stat && stat.size || 0; - - total += size; + function calcSize(error, size) { + if (!error) + total += size; } processDir(dir, calcSize, function(error) { @@ -45,26 +44,38 @@ }; function processDir(dir, func, callback) { - var asyncRunning = 0, - fileCounter = 1; - - function getDirInfo(dir) { - stat(dir, Util.exec.with(getStat, dir)); - } + var asyncRunning = 0, + fileCounter = 1, + + execCallBack = function () { + if (!fileCounter && !asyncRunning) + Util.exec(callback); + }, + + getDirInfo = function(dir) { + stat(dir, Util.exec.with(getStat, dir)); + }; + + getDirInfo(dir); function getStat(dir, error, stat) { + var isFile, isDir; + --fileCounter; - if (error) + if (error) { callback(error); - else - if (stat.isFile()) - Util.exec(func, stat); - else if (stat.isDirectory()) { + } else { + isFile = stat.isFile(), + isDir = stat.isDirectory(); + + if (isFile) + func(null, stat.size); + else if (isDir) { ++asyncRunning; fs.readdir(dir, function(error, files) { - var dirPath, file, n, i; + var getInfo, dirPath, file, n, i; asyncRunning--; @@ -75,8 +86,9 @@ for (i = 0; i < n; i++) { file = files[i]; dirPath = path.join(dir, file); + getInfo = Util.exec.with(getDirInfo, dirPath); - process.nextTick(getDirInfo.bind(null, dirPath)); + process.nextTick(getInfo); } } @@ -84,16 +96,10 @@ execCallBack(); }); } + } execCallBack(); } - - function execCallBack() { - if (!fileCounter && !asyncRunning) - Util.exec(callback); - } - - getDirInfo(dir); } })();