I am using node-mysql driver for a node.js app. Instead of having to set-up the mysql connection over and over again for each of my model-like modules, I do this:
// DB.js
var Client = require('mysql').Client;
var DB_NAME = 'test_db';
var client = new Client();
client.user = 'user';
client.password = 'pass';
client.connect();
client.query('USE '+DB_NAME);
module.exports = client;
// in User.js
var db = require("./DB");
// and make calls like:
db.query(query, callback);
Now, I notice that DB.js is initialised with the DB connection only once. So, subsequently the same client
object is being used... How do I structure DB.js such that when I require it from a model, every time a new DB connection will be set-up? I know it's got something to do with using new
, but I am not able to wrap my head around it.
Create a package.json file, on the command line, in the root directory of your Node. js module, run npm init : For scoped modules, run npm init --scope=@scope-name. For unscoped modules, run npm init.
Nodejs Core Modules: js installation process are known as core modules. To load/include this module in our program, we use the require function. The return type of require() function depends on what the particular module returns. Http, file system and url modules are some of the core modules.
A package in Node. js contains all the files you need for a module. Modules are JavaScript libraries you can include in your project.
url module includes methods for URL resolution and parsing. querystring module includes methods to deal with query string. path module includes methods to deal with file paths. fs module includes classes, methods, and events to work with file I/O.
module.exports = function() {
var client = new Client();
client.user = 'user';
client.password = 'pass';
client.connect();
client.query('USE '+DB_NAME);
return client;
}
var db = require("./DB")()
Initialize a new client each time you call the database.
You could use Object.defineProperty
to define exports
with custom getter logic so you can do var db = require("./DB")
if you want.
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