I am looking for subjective advice (and I know this might get closed), but I want to be able to separate routes and controllers in a node.js project so I have some questions:
index.js
but that seems odd. I am already doing app.get("/" controllers.index);
style separation, but I am getting hung up on building a module that just includes all JS files in another module. Am I missing something?If you wanted to get it all into one file, you might try something like this, which requires every file in ./routes/
and calls the function exported to each with app
as the 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 also some interesting examples in Express' example
directory on GitHub, such as an MVC-based one which implements RESTful routes much like Rails would.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With