如何传递节点express应用程序的对象? [英] How do you pass objects around node express application?

查看:95
本文介绍了如何传递节点express应用程序的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用express和node-postgres构建节点应用程序( https://github.com/ brianc /节点postgres的)。我只想建立数据库客户端连接一次,我希望能够从不同的模块访问这个数据库连接。什么是最好的方法呢?我试图只导出数据库连接,而不是整个快速应用程序。本质上,跨节点应用程序导出和访问对象的最佳方法是什么?



我已经查看了这个类似的问题,但它似乎是特定于mongoose的。 >

与mongoose / node.js共享数据库连接参数的最佳方式

解决方案

没有一个名为最好的办法。如果您需要在不同模块中使用相同的对象,则必须将其包装在模块中。这样做:

  // db.js 
var postgres = require(...)
var连接;

module.exports = {
getConnection:function(){
return connection;
},
createConnection:function(){
connection = createConnection(postgress);
}
};

//app.js - 主文件
require(./db\").createConnection();

//a.js
var db = require(./ db)
db.getConnection()

//b.js
var db = require(./ db)
db.getConnection()


I am building a node application using express and node-postgres (https://github.com/brianc/node-postgres). I only want to build the db client connection once, and I'd like to be able to access this db connection from different modules. What is the best way to do this? I'm trying to only export the db connection, not the whole express app. Essentially, what's the best way to export and access objects across a node application?

I've checked out this similar question, but it seems specific to mongoose.

Best way to share database connection param with mongoose/node.js

解决方案

There's not a thing called "the best way". If you need to use the same object among different modules you have to wrap it in a module. Something like this:

//db.js
var postgres = require (...)
var connection;

module.exports = {
  getConnection: function (){
    return connection;
  },
  createConnection: function (){
    connection = createConnection (postgress);
  }
};

//app.js - main file
require ("./db").createConnection ();

//a.js
var db = require("./db")
db.getConnection()

//b.js
var db = require("./db")
db.getConnection()

这篇关于如何传递节点express应用程序的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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