如何在节点快递应用程序周围传递对象?

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

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

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

没有什么叫“最好的方式”。 如果你需要在不同的模块中使用相同的对象,你必须把它包装在一个模块中。 像这样的东西:

//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() 

你可以做这样的事情..

 //db.js var pg = require('pg'); var conString = "tcp://postgres:1234@localhost/postgres"; module.exports.connectDatabase = function(callback){ var client = new pg.Client(conString); client.connect(function(err) { if(err){ console.log(err); process.exit(1); } module.exports.client = client; callback(); }) //app.js // We are trying to connect to database at the start of our app and if it fails we exit the process var db = require('./db'); db.connectDatabase(function(){ // your other code }) //a.js var db = require('./db'); //you can access your client here to perform database operations like that db.client