Is it possible to automate routing in Express?

Problem

Is it possible to automate routing in Express, so I don't have to list out all the routes?

For example: going to URL '/users/first_example' should automatically use the "users.first_example" module.

app.get('/users/:name', function(req,res){
return eval('users.'+req.params.name); //failed attempt
});

There's got to be something I'm missing, and it would make my code look a lot more elegant.

Much appreciated.

Problem courtesy of: Adam

Solution

var users = require('./users');//a module of route handler functions
app.get('/users/:name', function(req,res){
  var handler = users[req.params.name];
  if (typeof handler === 'function') {
    return handler(req, res);
  }
  res.status(404).render('not_found');
});
Solution courtesy of: Peter Lyons

Discussion

You might want to check this earlier answer on stackoverflow - https://stackoverflow.com/a/6064205/821720

A little more code but abstracts routing to the next level and also gives you a cleaner main file.

Discussion courtesy of: Mukesh Soni

I have been working on something like this, focused on REST routes. Take a look at https://github.com/deitch/booster

If your routes are RESTful:

var booster = require('booster'), express = require('express'), app = express(), db = require('./myDbSetup');

booster.init({app:app,db:db});
booster.resource('user');

app.listen(3000);

You just need to wire up the database/persistence connection layer. You can choose to customize the controller routes, or the models, or any part of it, but all optional.

Discussion courtesy of: deitch

This recipe can be found in it's original form on Stack Over Flow.