Skip to content

Instantly share code, notes, and snippets.

@jamescrowley
Created February 21, 2014 11:09
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 jamescrowley/9132561 to your computer and use it in GitHub Desktop.
Save jamescrowley/9132561 to your computer and use it in GitHub Desktop.
Get files in folder in specific order
Add a bundle.json file in the folder with the list of specific files
["file1","file2"]
and will then include all the other files in the directory
function readJson(file) {
return JSON.parse(fs.readFileSync(file, 'utf8'));
}
function getFilesInFolder(dir) {
console.log("Exploring " + dir);
return fs.readdirSync(dir)
.map(function(fileName) {
var filePath = path.join(dir, fileName);
var stat = fs.statSync(filePath);
var ext = path.extname(filePath);
return { filePath: filePath, fileName: fileName, isDirectory: stat.isDirectory(), fileExtension: ext }
})
.map(function(fileInfo) {
if (fileInfo.isDirectory) {
return getFilesInFolder(fileInfo.filePath)
} else {
return [fileInfo];
}
}).reduce(function(previous,current) { return previous.concat(current); });
}
function getOrderedFilesInFolder(dir,fileExtension) {
var filesInFolder = getFilesInFolder(dir)
.filter(function(fileInfo){
return fileInfo.fileExtension === fileExtension;
})
.map(function(fileInfo) { return fileInfo.filePath; });
var bundleConfigFile = path.join(dir,'bundle.json');
if (fs.existsSync(bundleConfigFile))
{
console.log('reading config ' + bundleConfigFile)
var config = readJson(bundleConfigFile)
.map(function(fileName) { return path.join(dir, fileName) })
.reverse();
config.forEach(function(filePath) {
var index = filesInFolder.indexOf(filePath);
filesInFolder.splice(index, 1);
filesInFolder.unshift(filePath)
});
}
return filesInFolder;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment