Search code examples
mysqlnode.jsexpressnode-mysql

Express JS how to include node-mysql object from a different file


I want to include my mysql connection from the same file(in case I have to change sql password or anything I don't want to change in a many files).

Here is my mysql.js file:

module.exports = require('mysql').createConnection(
  {
      host     : 'localhost',
      user     : 'admin',
      password : 'xxxxxxxx',
      database : 'database'
  }

);

and I want to use like this:

var connection = require(__dirname + '/../../../mysql');
connection.connect();
.
.
.

My problem is it's working only once. When I start the server I can query without any issues, but in the second query I got the following error message in the console:

"Cannot enqueue Handshake after invoking quit."

Does anybody has an idea why not working?


Solution

  • Thanks the help, but I found a solution for my problem. I just created the variables on my mysql.js file then I exported them like this:

    var host = 'localhost';
    module.exports.localhost = localhost;
    

    After I can use it on another js file:

    var connection = require(__dirname + '/../../../mysql');
    
    connection.localhost;
    

    I found it on this article: http://openmymind.net/2012/2/3/Node-Require-and-Exports/