开发者

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜