Created
August 10, 2012 09:34
-
-
Save liangzan/3312957 to your computer and use it in GitHub Desktop.
Read directories recursively with Node.js
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
var fs = require('fs') | |
, async = require('async') | |
, _ = require('underscore'); | |
/** | |
* Utility - for functions that do not belong anywhere | |
* | |
* @namespace - utility | |
*/ | |
var utility = exports; | |
utility.readdirRecursive = function(dirPath, callback) { | |
function mapPath(filePath, mapCallback) { | |
return fs.stat(filePath, function(err, stats) { | |
if (err) { | |
return mapCallback(err, filePath); | |
} else { | |
if (stats.isFile()) { | |
return mapCallback(null, filePath); | |
} else if (stats.isDirectory()) { | |
return utility.readdirRecursive(filePath, mapCallback); | |
} else { | |
return mapCallback(null, filePath); | |
} | |
} | |
}); | |
}; | |
fs.readdir(dirPath, function(err, files) { | |
if (err) { | |
return callback(err, null); | |
} else { | |
var fullFilePaths = _.map(files, function(filePath) { | |
return dirPath + '/' + filePath; | |
}); | |
return async.map(fullFilePaths, mapPath, function(err, mappedPaths) { | |
return callback(err, _.flatten(mappedPaths)); | |
}); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment