Skip to content

Instantly share code, notes, and snippets.

@andy-s-clark
Last active December 27, 2015 17:49
Show Gist options
  • Save andy-s-clark/7364899 to your computer and use it in GitHub Desktop.
Save andy-s-clark/7364899 to your computer and use it in GitHub Desktop.
Find folders matching the pattern themes/{theme}/assetnodes/{site} using NodeJS
/**
* Demo to find folders matching the pattern themes/{theme}/assetnodes/{site}
* Requires running `npm install async`
* Runs both using sync and async calls
* @TODO More error checking
*/
var fs = require('fs');
var async = require('async');
var basePath = '../BuildStore/themes';
var assetNodes = 'assetnodes';
fs.readdir(basePath, function(err, themes) {
if (!err) {
var syncResults = [];
for(var i=0; i<themes.length; i++) {
var stats = fs.statSync(basePath+'/'+themes[i]);
var assetNodesPath = basePath+'/'+themes[i]+'/'+assetNodes;
if ( stats.isDirectory() && fs.existsSync(assetNodesPath) ) {
sites = fs.readdirSync(assetNodesPath);
for (var j=0; j<sites.length; j++) {
var filePath = assetNodesPath+'/'+sites[j];
var stats = fs.statSync(filePath);
if ( stats.isDirectory() ) {
syncResults.push(filePath);
}
}
}
}
console.log('==synchronous results==');
console.log(syncResults);
console.log('\n\n');
var paths = [];
for (var i=0; i<themes.length; i++) {
paths.push(basePath+'/'+themes[i]);
}
async.map(paths, fs.stat, function(err, fileStats) {
if (!err) {
var assetNodesPaths = [];
for(var i=0; i<paths.length; i++) {
if ( fileStats[i].isDirectory() ) {
assetNodesPaths.push(paths[i]+'/'+assetNodes);
}
}
async.filter(assetNodesPaths, fs.exists, function(directoryPaths) {
async.map(directoryPaths, fs.readdir, function(err, files) {
var subDirPaths = [];
for(var i=0; i<files.length; i++) {
for(var j=0; j<files[i].length; j++) {
subDirPaths.push(directoryPaths[i]+'/'+files[i][j]);
}
}
async.map(subDirPaths, fs.stat, function(err, fileStats) {
var asyncResults = [];
for(var i=0; i<fileStats.length; i++) {
if(fileStats[i].isDirectory()) {
asyncResults.push(subDirPaths[i]);
}
}
console.log('==asynchronous results==');
console.log(asyncResults);
});
});
});
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment