在node.js中共享对象和避免全局变量 [英] Sharing objects and avoiding globals in node.js

查看:173
本文介绍了在node.js中共享对象和避免全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用我的路由器/控制器在下面的代码片段( db 变量)中共享数据库连接最合适的方式是什么,而不转动 db 变量到全局?

What would be the most appropriate way of sharing the database connection in the below snippet ( the db variable) with my routers/controllers without turning the db variable into a global?

var mongo = require('mongoskin'),
db = mongo.db(config.db.adress);

app.use(function(req, res, next) {
    db.open(function(err, data) {
        (err) ? res.send('Internal server error', 500) : next();
    });
});

// Setting up controllers here
app.post('/users', require('./controllers/users').create);

从PHP背景出发,我考虑了依赖注入但是我不知道这是否适用于节点。

Coming from a PHP background, I came to think about Dependency Injection, but I have no idea if that's appropriate in node.

推荐答案

尝试看这样:

app.js:

var mongo = require('mongoskin'),
db = mongo.db(config.db.adress);

app.use(function(req, res, next) {
    db.open(function(err, data) {
        (err) ? res.send('Internal server error', 500) : next();
    });
});

require('./controllers/users')(app, db);

controllers / users.js:

controllers/users.js:

module.exports = function (app, db) {

    app.post('/users', function(req, res, next) {
        // Your create function
        // Link to db exists here
    });

};

这篇关于在node.js中共享对象和避免全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆