Skip to content

Instantly share code, notes, and snippets.

@liangzan
Created August 10, 2012 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liangzan/3312957 to your computer and use it in GitHub Desktop.
Save liangzan/3312957 to your computer and use it in GitHub Desktop.
Read directories recursively with Node.js
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