Created
March 1, 2012 09:33
-
-
Save yuest/1948558 to your computer and use it in GitHub Desktop.
列出目录下的所有目录和文件
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
exports.dirs_files = function dirs_files(dir, callback) { | |
var returned = false | |
, result = { dirs: [], files: [] } | |
, remaining = 1 | |
if ('function' === typeof dir) { | |
callback = dir | |
dir = '.' | |
} | |
if ('.' === dir[0]) { | |
dir = path.resolve(dir) | |
} | |
function errorWrap (fn) { | |
return function(err) { | |
if (returned || err) { | |
if (!returned) { | |
returned = true | |
return callback(err) | |
} | |
return | |
} | |
fn.apply(this, Array.prototype.slice.call(arguments, 1)) | |
} | |
} | |
function dirs (dir) { | |
result.dirs.push(dir) | |
fs.readdir(dir, errorWrap(function(files) { | |
remaining += files.length | |
files.forEach(function(file) { | |
file = path.resolve(dir, file) | |
fs.stat(file, errorWrap(function(stats) { | |
if (stats.isFile()) { | |
result.files.push(file) | |
--remaining || done() | |
} else if (stats.isDirectory()) { | |
dirs(file) | |
} else { | |
--remaining || done() | |
} | |
})) | |
}) | |
--remaining || done() | |
})) | |
} | |
function done () { | |
callback(null, result) | |
} | |
fs.stat(dir, function(err, stats) { | |
if (err) { | |
callback(err) | |
} else if (!stats.isDirectory()) { | |
callback(new Error('first parament is not a directory path')) | |
} else { | |
dirs(dir) | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment