Node.js - 模块只初始化一次吗?
我正在为 node.js 应用程序使用 node-mysql 驱动程序。我不必为每个类似模型的模块一遍又一遍地设置 mysql 连接,而是这样做:
// 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);
现在,我注意到 DB.js 仅使用数据库连接初始化一次。因此,随后使用相同的 client
对象...我如何构建 DB.js,以便当我从模型中需要它时,每次都会建立一个新的数据库连接?我知道这与使用 new
有关,但我无法理解它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每次调用数据库时都会初始化一个新的客户端。
您可以使用
Object.defineProperty
来定义带有自定义 getter 逻辑的exports
,这样您就可以执行var db = require("./DB")
if你想要的。Initialize a new client each time you call the database.
You could use
Object.defineProperty
to defineexports
with custom getter logic so you can dovar db = require("./DB")
if you want.