Reputation: 11543
in my app I share config variables this way:
const config = require('./config')
and config.js is a separate file:
module.exports = {
option1: value1,
option2: value2
};
If I change attributes in config
object dynamically,
does it affect other modules as well?
for example:
module.exports = { foo: 'bar' }
var config = require('./config');
module.exports.sayFoo = function () {
console.log(config.foo);
}
var config = require('./config');
var app1 = require('./app1');
config.foo = 'baz';
app1.sayFoo();
# node app2.js =====> ??
Upvotes: 1
Views: 1002
Reputation: 11543
Write. I'll see it myself.
I've tested two cases:
1) can you dynamically change a required module's attribute?
2) can you dynamically change what modules exports?
module.exports = { foo: 'bar' }
var config = require('./config');
var app2 = require('./app2');
config.foo = 'baz'; // change required module attribute
app2.sayFoo();
console.log(app2.haveFoo);
var config = require('./config');
module.exports.sayFoo = function () {
console.log(config.foo);
module.exports.haveFoo = true; //dynamic export
}
results
# node app1.js
baz
true
both cases work.
Upvotes: 1
Reputation: 1364
require in Node caches the response so if you call the same thing twice, it will use the cached version.
However, thkang is right. Just run it and you will see it for yourself.
Upvotes: 1