Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - are modules initialised only once?

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.

like image 826
jeffreyveon Avatar asked May 10 '11 17:05

jeffreyveon


People also ask

How do I initialize node modules?

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.

How modules are loaded in node JS?

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.

What is difference between module and package in node JS?

A package in Node. js contains all the files you need for a module. Modules are JavaScript libraries you can include in your project.

Which are 3 types of modules available in node JS?

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.


1 Answers

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.

like image 194
Raynos Avatar answered Oct 02 '22 19:10

Raynos