title: node.js design pattern for creating db connection once
body: <p>I am looking for help with a design pattern for creating a database connection in my node.js application.</p>
  
  <p>It seems obvious to do:</p>
  
  <p>module1:</p>
  
  <pre><code>var db;
  exports.get_db = function(callback) {
  
    if (db == null) {
      dblibrary.create(connection_params, function(error, conn) {
        if (error == null) {
          db = conn;
          callback(null, db);
        }
      });
    } else {
      callback(null, db);
    }
  };
  </code></pre>
  
  <p>module2:</p>
  
  <pre><code>exports.do_something = function () {
    module1.get_db(function (err, conn) {
      if (err == null) {
        // continue using query
      }
    });
  };
  </code></pre>
  
  <p>It seems painful to have to penalize every single person who wants to get the db connection with the requirement of using a callback.</p>
  
  <p>I could do this:</p>
  
  <p>module1:</p>
  
  <pre><code>var db;
  
  dblibrary.create_connection(connection_params, function (err, conn) {
  
    if (err != null) {
       console.log("can't create connection");
       console.log(err);
       process.exit();
    } else {
       db = conn;
    }
  });
  
  exports.get_db = function() {
    return db;
  };
  </code></pre>
  
  <p>This makes it so that getting the db connection is simple and fast, but means we have to "wait" at node startup time for the connection to be established.</p>
  
  <p>Which is the better design?  Is there a better way of doing things?</p>