How do you pass objects around node express application?


I am building a node application using express and 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


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:

var postgres = require (...)
var connection;

module.exports = {
  getConnection: function (){
    return connection;
  createConnection: function (){
    connection = createConnection (postgress);

//app.js - main file
require ("./db").createConnection ();

var db = require("./db")

var db = require("./db")
Solution courtesy of: Gabriel Llamas


You can do something like that..

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) {

  module.exports.client = client;

// 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');
  // your other code

var db = require('./db');
//you can access your client here to perform database operations like that
Discussion courtesy of: khurrum qureshi

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