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?)
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With