[英]Felixge/Node-Mysql Separate Connection File
I am attempting to use felixge/node-mysql in Node for my node app. 我正在尝试为我的节点应用程序在Node中使用felixge / node-mysql。 However, instead of the usual
但是,不是通常的
mysql.createConnection(...)
in the app.js, I wanted it separate as a "config" file. 在app.js中,我希望将其作为“配置”文件分开。 Right now in my config.js it is:
现在在我的config.js中是:
function localConnect(){
//Node Mysql dependency npm install mysql@2.0.0-alpha7
return require('mysql').createConnection({
hostname: 'localhost',
user: 'username',
password: 'password',
database: 'database'
});
}
and in app js: 并在应用js中:
...
//Node Mysql dependency npm install mysql@2.0.0-alpha7
var mysql = require('mysql');
//MYSQL database config file
var connection = require('./config.js').localConnect();
connection.connect();
and connection.connect() fails. 和connection.connect()失败。
The purpose is so that I can commit it to my repo without exposing my DB connection info and still provide a dbSample file for the user incase they wish to use it. 目的是使我可以在不暴露数据库连接信息的情况下将其提交到我的仓库中,并在用户希望使用它的情况下仍为用户提供dbSample文件。
Any suggestions? 有什么建议么?
Thanks! 谢谢!
I did not know about exporting in Node so as per Nick's hint, the following code works for config.js: 我不知道在Node中进行导出,因此按照Nick的提示,以下代码适用于config.js:
var mysql = function localConnect(){
//Node Mysql dependency npm install mysql@2.0.0-alpha7
return require('mysql').createConnection({
hostname: 'localhost',
user: 'username',
password: 'password',
database: 'database'
});
}
module.exports.localConnect = mysql;
In the app.js: 在app.js中:
//MYSQL database config file
var connection = require('./config.js').localConnect();
connection.connect(); //Successful
Another option: 另外一个选项:
db-config.js DB-config.js
module.exports = {
hostname: 'localhost',
user: 'username',
...
};
db.js db.js
var config = require('./db-config');
module.exports = require('mysql').createConnection(config);
app.js app.js
var db = require('./db.js');
db.query('SELECT ?', [ 1 ], function (err, data) { ... });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.