I have an NodeJS Express app that is getting really big in just one file (app.js).
I want to export all my routes into a single, external file, say ./lib/routes.j
What I do is group my routes by controller. For each group of related routes (users, shopping cart, whatever), I make a controller file that lives in app/controllers/foo.js
where foo
is the controller name. In my main javascript server file (where all your code currently lives), I require
each controller by name and then call its setup
function, passing in my express app
object, and allow the controller to add whatever routes it needs.
['api', 'authorization', 'users', 'tests'].map(function(controllerName) {
var controller = require('./controllers/' + controllerName);
controller.setup(app);
});
Inside each controller, I do something like:
exports.setup = function(app) {
app.get('/dashboard', function(req, res) {
res.render('dashboard', {
username: req.session.username
});
});
};