title: Node.js DRY with MySQL clients
body: <p>so here's a quick question. Basically I'm making an express application that connects to a MySQL server. Pretty simple. But how do I stop adding all the connection code between files so I don't have to change multiple files if I change password or database.</p>
  
  <p>Example:</p>
  
  <p><code>app.coffee</code></p>
  
  <pre><code>client = mysql.createClient
    user: config.db.user,
    password: config.db.pass
  
  app.get '/', routes.index
  </code></pre>
  
  <p><code>routes/index.coffee</code></p>
  
  <pre><code>client = mysql.createClient
    user: config.db.user,
    password: config.db.pass
  
  exports.index = (req, res) -&gt;
    res.render 'index'
  </code></pre>
  
  <p>I've tried to create a file called <code>lib/mysql.coffee</code> which is the following:</p>
  
  <pre><code>config = require '../config'
  mysql = require 'mysql'
  
  module.exports = ( -&gt;
    mysql.createClient
      host: config.db.host
      user: config.db.user
      password: config.db.pass
      database: config.db.name
  )
  </code></pre>
  
  <p>So in app, I can go: </p>
  
  <pre><code>mysql = require './lib/mysql'
  mysql.query 'SHOW TABLES', (err,r,f) -&gt;
      console.log err
  </code></pre>
  
  <p>but it keeps giving:</p>
  
  <pre><code>TypeError: Object function () {
      return mysql.createClient({
        host: config.db.host,
        user: config.db.user,
        password: config.db.pass,
        database: config.db.name
      });
    } has no method 'query'
  </code></pre>
  
  <p>Module: <a href="https://github.com/felixge/node-mysql" rel="nofollow">https://github.com/felixge/node-mysql</a></p>