Reputation: 2416
Using latest stable node.js and express from npm, I've created my first express project.
The default generated app defines routes/index.js, which contains a single route that renders the default index view.
I immediately assumed I could add other .js files to the routes/ folder and they would be included. This didn't pan out. Only routes/index.js is ever included. Adding additional routes to routes/index.js works fine.
What is the proper way to define and organize Express routes, following the structure provided by the express project generator?
The answer, paraphrasing the article at DailyJS:
Given the following routes:
app.get('/', function() {});
app.get('/users', function() {});
app.get('/users/:id', function() {});
... Create the following files:
routes/
├── index.js
├── main.js
└── users.js
Then, inside of routes/index.js:
require('./main');
require('./users');
For each new group of related routes, create a new file in routes/ and require() it from routes/index.js. Use main.js for routes that don't really fit in the other files.
Upvotes: 28
Views: 10454
Reputation: 23060
I prefer dynamically loading routes instead of having to manually add another require each time you add a new route file. Here is what I am currently using.
var fs = require('fs');
module.exports = function(app) {
console.log('Loading routes from: ' + app.settings.routePath);
fs.readdirSync(app.settings.routePath).forEach(function(file) {
var route = app.settings.routePath + file.substr(0, file.indexOf('.'));
console.log('Adding route:' + route);
require(route)(app);
});
}
I call this when the application loads, which then requires all files in the routePath. Each route is setup like the following:
module.exports = function(app) {
app.get('/', function(req, res) {
res.render('index', {
title: 'Express'
});
});
}
To add more routes, all you have to do now is add a new file to the routePath directory.
Upvotes: 20