Using separate controllers and routes in Node.js

I am looking for subjective advice (and I know that it can be closed), but I want to be able to separate routes and controllers in a node.js project, so I have a few questions:

  • Is it futile to try to make the node.js philosophy have fewer / more JS files?
  • I want to be able to require ("routing") and connect 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 weird. I am already doing the styles section app.get("/" controllers.index); , but I am addicted to creating a module that includes only all JS files in another module. Did I miss something?
  • Or maybe there is a completely different style of node.js, and I'm trying to match my ASP.NET MVC knowledge too deeply?
+7
source share
2 answers

If you want to get all this into one file, you can try something like this, which requires each file in ./routes/ and calls a function exported to each using app as a 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 several interesting examples in the Express' example directory on GitHub, for example based on MVC , which implements RESTful routes like Rails.

+7
source
0
source

All Articles