javascript - NodeJS proper practice for route structure -


over past few days have been researching best practice using controllers , routes in nodejs. wanted split controllers, models, middlewares , routes instead of having cluttered routes page.

finally have came working solution, wanted input more efficient method? feel seems bit basic now, please ask questions.

directory structure

macbook-pro:v1 macplusaday$ tree . ├── app.js ├── bin │   └── www ├── controllers │   ├── index.js │   └── user.js ├── middlewares ├── models ├── npm-debug.log ├── package.json ├── public │   ├── images │   ├── javascripts │   └── stylesheets │       └── style.css ├── routes │   ├── index.js │   └── users.js └── views     ├── error.jade     ├── index.jade     └── layout.jade 

app.js using method include of route files app.js file, feel easier having separately include each individual routes file.

var normalizedpath = require("path").join(__dirname, "routes");  require("fs").readdirsync(normalizedpath).foreach(function(file) {     app.use('/', require("./routes/" + file)); }); 

routes/index.js have seperated each route class functionality been run inside controller classes. there can multiple of these route files, e.g. 1 users , 1 posts.

var express = require('express'); var router = express.router();  var indexcontroller = require('../controllers/index');  router.get('/', indexcontroller.getindex);  module.exports = router; 

controllers/index.js have separated functionality module export allow easy editing.

module.exports = {     //get / index page     getindex: function(req, res, next) {         res.render('index', {              title: 'express2'          });     } }; 


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -