1

I am using express js for my web application. what should be the proper directory structure for seperating routing and business logic. also how to communicate in between them

Pritam Kale
  • 33
  • 1
  • 1
  • 4
  • possible duplicate of [Folder structure for a Node.js project](http://stackoverflow.com/questions/5178334/folder-structure-for-a-node-js-project) – Gaurav Gupta Jun 10 '15 at 07:00

1 Answers1

0

I like to separate request handling, logic and response in three different folders.

  • ./js/server/request
  • ./js/server/response
  • ./js/server/model

This is how I like to separate things, and I will be pleased to have a feedback, or other separation techniques.

The following example is based on express.

var express = require('express');

First, in your main server file, declare a router, so you can handle requests in separate files :

var routeName = require('./js/server/request/routerName');
var app = express();
app.use(routeName);

then you can handle every request you want in this file. In this file, do not forget to export the router at the end :

module.exports = router;

and to import the proper stuff :

var express = require('express');

Now you can handle your routes :

var router = express.Router();
router.get('/', function (err, req, res, next) {
  // Put some route handling here
});

At this point, I extract data from the request that I need to "know what to do". Then, in the ./js/server/ directory, you can make two more folders : a response folder and a model folder.

Model folder : classes for "logic". Usually database communication, etc... Response folder : takes something from the model class and sends it back to the client.

In your router, it could look like that :

router.get('/', function (err, req, res, next) {
  var model = new Model();
  var response = new Response(req, res);
  model.doSomething(params, response);
});

Then the model does his work, and at the end, calls the response with accurate info to send !

fox_db
  • 58
  • 6