Last active
December 28, 2015 04:59
-
-
Save alepez/7446330 to your computer and use it in GitHub Desktop.
express recursive routing with namespace
This file contains hidden or 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 walk = function(dir, done) { | |
var results = {}; | |
fs.readdir(dir, function(err, list) { | |
if (err) { | |
return done(err); | |
} | |
var i = 0; | |
var next = function() { | |
var file = list[i]; | |
i += 1; | |
if (!file) { | |
return done(null, results); | |
} | |
file = dir + '/' + file; | |
fs.stat(file, function(err, stat) { | |
if (stat && stat.isDirectory()) { | |
walk(file, function(err, res) { | |
results[path.basename(file)] = res; | |
next(); | |
}); | |
} else { | |
results[path.basename(file, '.js')] = file; | |
next(); | |
} | |
}); | |
}; | |
next(); | |
}); | |
}; | |
var addNamespace = function(app, ns, tree) { | |
app.namespace('/' + ns, function() { | |
addRoute(app, tree); | |
}); | |
}; | |
var addRoute = function(app, tree) { | |
for ( var i in tree) { | |
if (typeof tree[i] == 'string') { | |
var module = require(tree[i]); | |
if (module.routes) { | |
module.routes(app); | |
} | |
} else { | |
addNamespace(app, i, tree[i]); | |
} | |
} | |
}; | |
module.exports = function(app) { | |
walk('./routes', function(err, tree) { | |
addRoute(app, tree); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment