简体   繁体   English

更改node.js模块变量

[英]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: 和config.js是一个单独的文件:

module.exports = {
  option1: value1,
  option2: value2
};

If I change attributes in config object dynamically, does it affect other modules as well? 如果我动态更改config对象中的属性,是否还会影响其他模块?

for example: 例如:

config.js config.js

module.exports = { foo: 'bar' }

app1.js app1.js

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

app2.js 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? 1)您可以动态更改所需模块的属性吗?

2) can you dynamically change what modules exports? 2)您可以动态更改导出的模块吗?

config.js config.js

module.exports = { foo: 'bar' }

app1.js 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 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. Node中的require会缓存响应,因此,如果您两次调用同一件事,它将使用缓存的版本。

However, thkang is right. 但是,thkang是正确的。 Just run it and you will see it for yourself. 只需运行它,您就会自己看到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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