所以這裏有一個簡單的問題。基本上我正在製作一個連接到MySQL服務器的快速應用程序。很簡單。但是,我如何停止添加文件之間的所有連接代碼,以便在更改密碼或數據庫時不必更改多個文件。Node.js DRY與MySQL客戶端
例子:
app.coffee
client = mysql.createClient
user: config.db.user,
password: config.db.pass
app.get '/', routes.index
routes/index.coffee
client = mysql.createClient
user: config.db.user,
password: config.db.pass
exports.index = (req, res) ->
res.render 'index'
我試圖創建一個名爲lib/mysql.coffee
文件,該文件是這樣的:
config = require '../config'
mysql = require 'mysql'
module.exports = (->
mysql.createClient
host: config.db.host
user: config.db.user
password: config.db.pass
database: config.db.name
)
因此,在應用程序,我可以去:
mysql = require './lib/mysql'
mysql.query 'SHOW TABLES', (err,r,f) ->
console.log err
但它一直給:
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'
模塊:https://github.com/felixge/node-mysql