Skip to content

Instantly share code, notes, and snippets.

@pawelrychlik
Created July 31, 2014 21:01
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 pawelrychlik/3939ac7b7d2a7c066b82 to your computer and use it in GitHub Desktop.
Save pawelrychlik/3939ac7b7d2a7c066b82 to your computer and use it in GitHub Desktop.
Directory tree walker & js file resolver
var fs = require("fs");
var path = require("path");
var util = require('util');
function Resolver(pathToDirectory) {
this.mappings = dirTree("initial-value", pathToDirectory).contents;
//console.log("[URL Resolver] Discovered mappings: %s", util.inspect(this.mappings, false, null));
}
function dirTree(name, filepath) {
var result = { name: name };
if (fs.lstatSync(filepath).isDirectory()) {
result.contents = {};
fs.readdirSync(filepath)
//-- now it's a list of strings, e.g. ["routes","a.js"] --
.map(function(child) {
return dirTree(child, filepath + '/' + child);
})
//-- now it's an array of objects, e.g. [ {name:"routes",contents: {}}, {name:"a.js",contents:fn()} ] --
.reduce(function(acc, curr) {
// from an array item to the accumulator object
result.contents[curr.name] = curr.contents; //-- reduce to: { name: contents } --
}, {});
//-- now it's reduced to { routes: {}, "a.js": fn() } --
} else if (/^[^_].*.js$/.test(filepath)) {
//-- is a *.js file whose name is not beginning with underscore --
result.contents = require(filepath);
}
return result;
}
module.exports = Resolver;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment