Express Folder Structure

From Logic Wiki
Jump to: navigation, search


Model View Controller

The MVC pattern helps in rapid and parallel development. For example, one developer can work on the view, while another one can work on creating the business logic in the controller.

Let’s take a look at an example of a simple user CRUD application.

project/
  controllers/
    users.js
  util/
    plugin.js
  middlewares/
    auth.js
  models/
    user.js
  routes/
    user.js
    router.js
  public/
    js/
    css/
    img/
  views/
    users/
      index.jade
  tests/
    users/
      create-user-test.js 
      update-user-test.js
      get-user-test.js
  .gitignore
  app.js
  package.json

controllers: Define your app route handlers and business logic

util: Writes utility/helper functions here which can be used by any controllers. For example, you can write a function like mergeTwoArrays(arr1, arr2).

middlewares: You can write middlewares to interpret all incoming requests before moving to the route handler. For example,

router.post('/login', auth, controller.login) where auth is a middleware function defined in middlewares/auth.js.

models: also a kind of middleware between your controller and the database. You can define a schema and do some validation before writing to the database. For example, you can use an ORM like Mongoose which comes with great features and methods to use in the schema itself

routes: Define your app routes, with HTTP methods. For example, you can define everything related to the user.

router.post('/users/create', controller.create)
router.put('/users/:userId', controller.update)
router.get('/users', controller.getAll)

public: Store static images in/img, custom JavaScript files, and CSS /css

views: Contains templates to be rendered by the server.

tests: Here you can write all the unit tests or acceptance tests for the API server.

app.js: Acts as the main file of the project where you initialize the app and other elements of the project.

package.json: Takes care of the dependencies, the scripts to run with the npm command, and the version of your project.

require(“./../../../../../../”) mess

There are different workarounds for this problem.

If you find any module getting popular and if it has logical independence from the application, you can convert it to private npm module and use it like any other module in package.json.

OR

const path  = require('path');
const HOMEDIR  = path.join(__dirname,'..','..');

where __dirname is the built-in variable that names the directory that contains the current file, and .. ,..is the requisite number of steps up the directory tree to reach the root of the project.

From there it is simply:

const foo = require(path.join(HOMEDIR,'lib','foo'));
const bar = require(path.join(HOMEDIR,'lib','foo','bar'));