2013-04-17 18 views
4

我正在使用express和node-postgres構建節點應用程序(https://github.com/brianc/node-postgres)。我只想建立一次數據庫客戶端連接,我希望能夠從不同的模塊訪問這個數據庫連接。做這個的最好方式是什麼?我試圖只導出數據庫連接,而不是整個快遞應用程序。從本質上講,跨節點應用程序導出和訪問對象的最佳方式是什麼?如何在節點快遞應用程序周圍傳遞對象?

我已經簽出這個類似的問題,但似乎特定於貓鼬。

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

回答

3

這裏沒有一個所謂的 「最佳途徑」 的事情。如果您需要在不同模塊中使用相同的對象,則必須將其包裝在模塊中。事情是這樣的:

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

你可以做這樣的事情..

//db.js 
var pg = require('pg'); 

var conString = "tcp://postgres:[email protected]/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 
相關問題