1 Feb

Taking Toddler Steps with Node.js – Express Routing Revisited

Category:UncategorizedTag: :

Last year I wrote this blog post where I described a couple of ways on how to tackle routing with Express. In the mean while I moved on from the “Plain Old School” approach to an approach where I replaced underscore.js with node-require-directory.

Setting up node-require-directory is quite easy. In the routes folder, we just need to add an index.js module with the following two lines:

var requireDirectory = require('require-directory');
module.exports = requireDirectory(module);

Setting up the routes for Express then looks like this:

var routes = require('./../routes');

// Setting up an application ...

application.get('/', routes.root);
application.get('/home', routes.home);
application.get('/signin', routes.authentication.signin);
application.post('/signout', routes.authentication.signout);

// More route registrations

Here we simple reference the index.js module. The node-require-directory module takes care of building up a tree of functions which we can now access for our route registrations. Adding a new route is as simple as creating a new module somewhere inside the routes folder or one of its subfolders and creating a new route registration. Have a look at this example.

I found this little gem to be quite useful and it might be helpful for some of you as well.

Until next time.

Find me