nodejs mysql如何读取配置参数

时间:2013-04-22 13:15:41

标签: node.js node-mysql

var iniparser = require('iniparser');
var config = iniparser.parseSync('../Config/init/db.ini');
var env = process.env.NODE_ENV || 'dev'; //startup nodejs with e.g:  NODE_ENV= node server.js

var app                 = require('http').createServer(handler),
io                  = require('socket.io').listen(app),
fs                  = require('fs'),
mysql               = require('mysql'),
connectionsArray    = [],
connection          = mysql.createConnection({
    host        : config[env]['host'],
    user        : config[env]['user'],
    password    : config[env]['pwd'],
    database    : config[env]['dbname']
}),
POLLING_INTERVAL = 3000,
pollingTimer;    

console.log(config[env]['host']);
console.log(config[env]['user']);
console.log(config[env]['pwd']);
console.log(config[env]['dbname']);

// If there is an error connecting to the database
connection.connect(function(err) {
  // connected! (unless `err` is set)
  console.log( err );
});

db.ini

 [dev]
 host = "localhost"
 user = "root"
 pwd =  "root"
 dbname = "db_local"

从console.log输出:

"localhost"
"root"
"root"
"tittilate_local"

我的nodejs脚本的这一部分。 console.log正在输出正常但未建立连接。 不知何故,在createConnection中无法识别config变量。

有人有建议吗?

1 个答案:

答案 0 :(得分:1)

INI文件值不应该用引号分隔,否则这些引号将成为值的一部分。

所以在你的情况下,试试这个:

[dev]
host   = localhost
user   = root
pwd    = root
dbname = db_local