If you want to get all this into one file, you can try something like this, which requires each file in ./routes/ and calls a function exported to each using app as a parameter:
// routing.js var fs = require('fs'); module.exports = function(app) { fs.readdirSync(__dirname + '/routes/').forEach(function(name) { var route = require('./routes/' + name); route(app); }); } // routes/index.js module.exports = function(app) { app.get('/something', function(req, res) { ... }); app.get('/something/else', function(req, res) { ... }); } // routes/pages.js module.exports = function(app) { app.get('/pages/first', function(req, res) { ... }); app.get('/pages/second', function(req, res) { ... }); } // server.js var app = express.createServer(); require('./routing')(app); // require the function from routing.js and pass in app
There are several interesting examples in the Express' example directory on GitHub, for example based on MVC , which implements RESTful routes like Rails.
Michelle tilley
source share