2013-04-17 4 views
4

익스프레스 및 노드 포스트그레스 (https://github.com/brianc/node-postgres)를 사용하여 노드 애플리케이션을 구축 중입니다. DB 클라이언트 연결을 한 번만 빌드하고 싶습니다. 다른 모듈에서이 db 연결에 액세스 할 수 있기를 원합니다. 이 작업을 수행하는 가장 좋은 방법은 무엇입니까? db 연결 만 내보내려고하는데, 전체 익스프레스 앱이 아닙니다. 기본적으로 노드 응용 프로그램에서 객체를 내보내고 액세스하는 가장 좋은 방법은 무엇입니까?노드 익스프레스 애플리케이션에서 객체를 전달하는 방법은 무엇입니까?

나는이 비슷한 질문을 체크 아웃했지만 몽구스에만 해당하는 것으로 보입니다.

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 
관련 문제