Created
February 21, 2014 11:09
-
-
Save jamescrowley/9132561 to your computer and use it in GitHub Desktop.
Get files in folder in specific order
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
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 |
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
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