Created
July 31, 2014 21:01
-
-
Save pawelrychlik/3939ac7b7d2a7c066b82 to your computer and use it in GitHub Desktop.
Directory tree walker & js file resolver
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
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