Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the same MySQL connection(s) for my entire Node.js app?

I have an app.js. I run my entire app from there.

Inside app.js, I require many files that have code in it.

For each of these files, I do this:

var mysql = require('mysql');
var mclient = mysql.createConnection({
    host: settings.MYSQL.HOST,
    user: settings.MYSQL.USER,
    password: settings.MYSQL.PASSWORD,
    database: settings.MYSQL.DB,
});

Essentially, I am initiating a new connection for every file.

I want my app.js to make ONE connection, and then pass it to every file during the require line. How can I pass the connection to them so those files can use it?

(Or how can I pass a pool of connections to them?)

like image 896
TIMEX Avatar asked Dec 15 '13 19:12

TIMEX


People also ask

How do you connect your node JS application to MySQL?

First, initialize the node. js project in the particular folder in your machine. Download the mysql module in the project folder. After this create connection to the database with the createconnection() method of the mysql module.

How do I provide a MySQL database connection in a single file in node JS?

var mysql = require('mysql'); var connection = mysql. createConnection({ host : '127.0. 0.1', user : 'root', password : '', database : 'chat' }); connection. connect(function(err) { if (err) throw err; }); module.


1 Answers

You can create a separate module, call it mysqlLib.js that will be responsible for creating a pool and returning connections:

var mysql = require("mysql");
var pool = mysql.createPool(/* credentials go here */);

exports.getConnection = function(callback) {
  pool.getConnection(function(err, conn) {
    if(err) {
      return callback(err);
    }
    callback(err, conn);
  });
};

and in any module/file that needs a mysql connection, you can do this:

var mysqlLib = require("mysqlLib");

mysqlLib.getConnection(function(err, mclient) {
  //do queries that you need
});

The way require() works, the code in mysqlLib.js will only be run once so only one pool will be created even if require("mysqlLib.js"} is called in multiple files. See this section of the node.js docs for an explanation of module cacheing.

like image 63
go-oleg Avatar answered Sep 20 '22 12:09

go-oleg