Skip to content

Instantly share code, notes, and snippets.

@pstephens
Last active January 4, 2016 07:59
Show Gist options
  • Save pstephens/8591893 to your computer and use it in GitHub Desktop.
Save pstephens/8591893 to your computer and use it in GitHub Desktop.
Recursively get a list of files given a starting path.
var _ = require('underscore');
var fs = require('fs');
var path = require('path');
var Q = require('Q');
function processFileAsync(context)
{
return Q.ninvoke(fs, "stat", context.path)
.then(function(stat) {
if(stat.isFile()) {
return [context];
}
else if(stat.isDirectory()) {
return readDirAsync(context);
}
else {
return [];
}
});
}
function readDirAsync(context)
{
return Q.ninvoke(fs, "readdir", context.path)
.then(function(files) {
return Q.all(_.map(files, function(file) {
return processFileAsync({
path: path.join(context.path, file),
key: context.key + (context.key === '' ? '' : '/') + file
});
}));
});
}
function getFilesRecursiveAsync(startingPath)
{
return readDirAsync({
key: "",
path: startingPath})
.then(function(nestedFileArrays) {
return _.flatten(nestedFileArrays);
});
}
function getRootDir() {
return path.normalize(path.join(__dirname, '../..'));
}
function getContentDir() {
return path.join(getRootDir(), "Content");
}
module.exports = {
getRootDir: getRootDir,
getContentDir: getContentDir,
getFilesRecursiveAsync: getFilesRecursiveAsync
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment