Edit required/exported variable in Nodejs

381 Views Asked by At

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 = {}
2

There are 2 best solutions below

2
On BEST ANSWER

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.

1
On

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.