How to include route handlers in multiple files in Express?

Problem

In my NodeJS express application I have app.js that has a few common routes. Then in a wf.js file I would like to define a few more routes.

How can I get app.js to recognize other route handlers defined in wf.js file?

A simple require does not seem to work.

Problem courtesy of: rafidude

Solution

If you want to put the routes in a separate file, for example routes.js, you can create the routes.js file in this way:

module.exports = function(app){

app.get('/login', function(req, res){
res.render('login', {
title: 'Express Login'
});
});

//other routes..
}

And then you can require it from app.js passing the app object in this way:

require('./routes')(app);

Have also a look at these examples

https://github.com/visionmedia/express/tree/master/examples/route-separation

Solution courtesy of: BFil

View additional discussion.