How do you pass objects around a node express application?

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

I checked this similar question, but it seems to be specific to the mongoose.

Best way to exchange database connection parameter with mongoose / node.js

+4
source share
2 answers

It’s not called the "best way." If you need to use the same object among different modules, you must wrap it in a module. Something like that:

//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() 
+3
source

You can do something like this.

 //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 
-2
source

All Articles