我正在使用 express 和 node-postgres ( https://github.com/brianc/node-postgres ) 构建 Node 应用程序。我只想建立一次数据库客户端连接,我希望能够从不同的模块访问这个数据库连接。做这个的最好方式是什么?我试图只导出数据库连接,而不是整个 express 应用程序。从本质上讲,跨 Node 应用程序导出和访问对象的最佳方式是什么?
我已经检查了这个类似的问题,但它似乎特定于 mongoose。
Best way to share database connection param with 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()
关于node.js - 您如何在 Node Express 应用程序周围传递对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16052736/