I have 2 files, db-config.js & util.js. db-config.js contains:
var db = exports.db = mysql.createConnection({
host: host,
database: dbName,
user: user,
password: password,
port: port
});
I want to export the db variable in util.js & edit it there so that any other file trying to access db variable from db-config.js gets the updated variable. What I tried is the code below but didn't work for me. Also all the files get the instance of db variable upon startup, so I want that once the variable gets updated, the updated one is available with all the files.
util.js contains:
var db= require('../../db/db-config').db;
db = {}
You can export a function that returns db instead of db itself.
var getDB = function() { return db; }
exports.getDB = exports.getDB;
You will have to make sure that you retrieve db before using it in your other files.
what about using config.json instead ?
config.json file will contain same info as what your db-config.js
{ "dbName":"xx", "host":"xxx.com", etc.. }
In your code, you will be
var config = getConfig('../config.json');
var host = config.host var dbName=config.dbName
etc..
If you db config changes all the time, you can dynamically generate the config.json.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.