N
N
Nikita Gusakov2014-11-04 02:38:16
Node.js
Nikita Gusakov, 2014-11-04 02:38:16

How do you organize your nodejs applications?

Let's say with sailsjs everything is clear. But what about express, hapi? I'm moving from Symfony, so I made a kind of service-locator from app and pass it directly to the controller constructor and it takes the necessary dependencies there. In the future, this can be resolved through a self-written two-line DI ...
But my question is - maybe there are some ready-made solutions?
Example code, using ES6

class UserController {
    constructor(app) {
        this.conn = app.get('conn');
        this.validator = app.get('validator');

        var router = new express.Router();
        router.get('', this.all.bind(this));
        router.get('/me', this.me.bind(this));
        app.use('/api/users', router);
    }
}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexander Kaloshin, 2014-11-05
@undassa

It's strange that no one suggested that you look towards the yeoman generator.
At the moment, the guys are just trying to create a standard for organizing applications in node and other languages.
In our applications, we use something like the following structure:

├── Gruntfile.js
├── app.js
├── config
│   ├── config.js
│   └── env
│       ├── all.js
│       ├── development.js
│       ├── production.js
│       └── staging.js
├── package.json
├── src
│   ├── controllers
│   │   └── controller.js
│   ├── lib - общие самописные библиотеки для всего приложения (например описание ошибок, логи и т.п.)
│   │   ├── error.js
│   │   ├── logger.js
│   │   └── routes.js
│   ├── modules - законченные модули
│       └── module.js
│   └── models - модель данных
│       └── model.js
└── templates
│       └── template.html

A
Alexander Wolf, 2014-11-04
@mannaro

With the organization of the application on the node, sorry, asshole. Everyone writes their bike. Most are clumsy.

K
Konstantin Kitmanov, 2014-11-04
@k12th

express is very low-level and is responsible for very basic things. Therefore, no organization of the code is provided, at least put everything in one file (and sometimes this is justified).
I personally use the structure that express generates + controllers, models, services and middlewares folders. Plus the settings folder, arranged like that in Django (if you're interested, I'll tell you more).

N
Nikita Gusakov, 2014-11-04
@hell0w0rd

Now app.js has resulted in this look:

var express = require('express');
var config = require('./config');
var middlewares = require('./middlewares');
var services = require('./services');
var controllers = require('./controllers');

var app = express();
app.set('config', config);
services(app);
middlewares.before(app);
controllers(app);
middlewares.after(app);

module.exports = app;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question