Last active
January 4, 2016 07:59
-
-
Save pstephens/8591893 to your computer and use it in GitHub Desktop.
Recursively get a list of files given a starting path.
This file contains hidden or 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 _ = 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