Shawn Wildermuth
Shawn Wildermuth

Reputation: 7458

Using separate controllers and routes in Node.js

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:

Upvotes: 8

Views: 4110

Answers (2)

kilianc
kilianc

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

Michelle Tilley
Michelle Tilley

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

Related Questions