javascript - Node.js - are modules initialised only once? - Stack Overflow

I am using node-mysql driver for a node.js app. Instead of having to set-up the mysql connection over a

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.

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.

Share Improve this question asked May 10, 2011 at 17:56 jeffreyveonjeffreyveon 13.9k18 gold badges86 silver badges141 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9
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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744955862a4603187.html

相关推荐

  • javascript - Node.js - are modules initialised only once? - Stack Overflow

    I am using node-mysql driver for a node.js app. Instead of having to set-up the mysql connection over a

    2天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信