How do you pass objects around node express application?

Problem

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

I've checked out this similar question, but it seems specific to mongoose.

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

Problem courtesy of: user2253099

Solution

There's not a thing called "the best way". If you need to use the same object among different modules you have to wrap it in a module. Something like this:

//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()
Solution courtesy of: Gabriel Llamas

Discussion

You can do something like that..

//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
Discussion courtesy of: khurrum qureshi

This recipe can be found in it's original form on Stack Over Flow.