admin管理员组文章数量:1410682
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.
1 Answer
Reset to default 9module.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.
本文标签: javascriptNodejsare modules initialised only onceStack Overflow
版权声明:本文标题:javascript - Node.js - are modules initialised only once? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744955861a2634350.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论