the routes in express
I'm really enjoying express. I think this is because unlike geddy, my experience with express is more closely tied to node itself than to a RVM pattern. I'm liking this, and learning more about node.
I loooove modules!
module.exports
is currently my favorite thing ever. On the client side of things I stick with requirejs, so I usually go with a define([deps], function() { returns AClass; });
sort of scheme for my modules. In node modularity is baked in, so any file gets wrapped in a function that includes a module object to which you would export the module to using module.exports
express routes
Using the structure/framework created by using express [opts]
from the cli, app.js includes a routes = requre('./routes')
object. As it turns out, node takes that to mean "get the module in ./routes/index.js
." Which is pretty awesome, but was originally confusing to me when I created ./routes/anotherRoute.js
and app.get('/anotherRoute', routes.anotherRoute)
didn't work.
The solution was actually pretty straightforward and seems to be a common pattern in node (though, I'm not sure how fond of it I am). Because node loads index.js automatically, I just exported anotherRoute
in there. So to get the nice, modular and concise app.get('/anotherRoute', routes.anotherRoute)
, so I use these little snippets, quite nicely:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | /* * GET home page. */ module.exports.index = function(req, res){ res.render('index', { title: 'My App', style: '/css/style.css' }); }; /* * GET another route module */ module.exports.anotherRoute = require('./anotherRoute').theOtherRoute; |
1 2 | app.get('/', routes.index); app.get('/anotherRoute', routes.anotherRoute); |
It still seems klugey?
I'm not really a fan of mixing concerns the way that ./routes/index.js
currently does so. In other words, in a future iteration index.js will act as a sort of “route aggregator,” if you will, that provides one point of contact for app.js to route everything. Also my route modules are a little redunant.
module.exports.anotherRoute = require('./anotherRoute').theOtherRoute;
should really be
module.exports.anotherRoute = require('./anotherRoute');
and app.js would wire it like so:
app.get('/anotherRoute', routes.anotherRoute.get);
app.put('/anotherRoute', routes.anotherRoute.put);
app.post('/anotherRoute', routes.anotherRoute.post);
I could use req.method
to call or apply this[req.method]
from routes.anotherRoute
, but I‘m not sure I’m comfortable with adding that concern to the module.