简体   繁体   中英

changing node.js module variable

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:

config.js

module.exports = { foo: 'bar' }

app1.js

var config = require('./config');
module.exports.sayFoo = function () {
    console.log(config.foo);
}

app2.js

var config = require('./config');
var app1 = require('./app1');
config.foo = 'baz';

app1.sayFoo();


# node app2.js =====> ??

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?

config.js

module.exports = { foo: 'bar' }

app1.js

var config = require('./config');
var app2 = require('./app2');
config.foo = 'baz'; // change required module attribute

app2.sayFoo();

console.log(app2.haveFoo);

app2.js

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.

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM