简体   繁体   English

如何重新链接库使用要求? (节点)

[英]How do I re-link the library use require? (nodejs)

For example I have file 1例如我有文件 1

[{"a1":1}]

And file 2文件 2

var obj1 = JSON.parse(fs.readFileSync("./файл 1.JSON" , "UTF-8"));
module.exports.obj1 = obj1

I start program ...我开始程序...

for(i=0; ; i++) {
  console.log(require('./файл 2').a1);
  let bb = JSON.parse(fs.readFileSync("./файл 1.JSON" , "UTF-8"));
  console.log(bb.a1);
  (there pause for slowed)
}

And at that time I correct file 1 .那时我更正了文件 1 Then I will see it in fs , but don't see in require .然后我会在fs 中看到它,但在require中看不到。 Now the question: how to make, so that require show the new value?现在的问题是:如何制作,以便要求显示新值?

When node executes your program and executes a require statement, it loads any modules.当 node 执行您的程序并执行require语句时,它会加载任何模块。 It then caches those modules so that subsequent requests for the same module give the same code.然后缓存这些模块,以便对同一模块的后续请求给出相同的代码。 So in your example, on the first time through the loop, file 2 is going to be initialized with whatever value it reads from the JSON file and it won't be re-initialized.因此,在您的示例中,在第一次循环时,文件 2 将使用它从 JSON 文件读取的任何值进行初始化,并且不会重新初始化。

Modules are intended to be static bundles of code and using require to include the same module multiple times is supposed to return the same module.模块旨在成为静态代码包,使用require多次包含同一个模块应该返回同一个模块。 For dynamic values like your JSON file, use fs functions to access the values at the time they're needed.对于像 JSON 文件这样的动态值,请使用fs函数在需要时访问这些值。

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

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