I am attempting to use felixge/node-mysql in Node for my node app. However, instead of the usual
mysql.createConnection(...)
in the app.js, I wanted it separate as a "config" file. Right now in my config.js it is:
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:
...
//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.
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.
Any suggestions?
Thanks!
I did not know about exporting in Node so as per Nick's hint, the following code works for 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:
//MYSQL database config file
var connection = require('./config.js').localConnect();
connection.connect(); //Successful
Another option:
db-config.js
module.exports = {
hostname: 'localhost',
user: 'username',
...
};
db.js
var config = require('./db-config');
module.exports = require('mysql').createConnection(config);
app.js
var db = require('./db.js');
db.query('SELECT ?', [ 1 ], function (err, data) { ... });