Node.js - modules initialized only once?

I am using the node-mysql driver for the node.js. application Instead of setting up the mysql connection over and over for each of my model 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 initialized with a DB connection only once. Thus, the same client object is subsequently used ... How can I structure DB.js in such a way that when I require it from the model, every time a new database connection is configured? I know this is due to the use of new , but I cannot wrap it around.

+6
source share
1 answer
 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 every time you invoke the database.

You can use Object.defineProperty to define exports with custom getter logic so you can do var db = require("./DB") if you want.

+9
source

Source: https://habr.com/ru/post/887754/


All Articles