Reputation: 7458
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?Upvotes: 8
Views: 4110
Reputation: 7806
If your intent is to do some RESTish API server, give it a try: https://github.com/kilianc/node-apiserver also examples: https://github.com/kilianc/node-apiserver/blob/master/examples
Upvotes: 0
Reputation: 159105
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.
Upvotes: 7