Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using separate controllers and routes in Node.js

Tags:

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:

  • Is it useless to try and is the node.js philosophy to have fewer/larger JS files?
  • I want to be able to require("routing") and have it wire up all my routes to the required module for my controllers. I can do this easily if I just put everything in 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?
  • Or maybe there is a completely different node.js style to do this, and I am trying to map my ASP.NET MVC knowledge too deeply?
like image 940
Shawn Wildermuth Avatar asked Jul 06 '12 20:07

Shawn Wildermuth


Video Answer


1 Answers

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.

like image 198
Michelle Tilley Avatar answered Oct 18 '22 02:10

Michelle Tilley