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.
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
Building on @ShadowCloud 's example I was able to dynamically include all routes in a sub directory.
routes/index.js
var fs = require('fs');
module.exports = function(app){
fs.readdirSync(__dirname).forEach(function(file) {
if (file == "index.js") return;
var name = file.substr(0, file.indexOf('.'));
require('./' + name)(app);
});
}
Then placing route files in the routes directory like so:
routes/test1.js
module.exports = function(app){
app.get('/test1/', function(req, res){
//...
});
//other routes..
}
Repeating that for as many times as I needed and then finally in app.js placing
require('./routes')(app);