javascript/nodejs 中的 require 是否每次在另一个模块中导入时都执行相同的文件?

Does require in javascript/nodejs executes same file everytime it is imported in another modules?

JavaScript/Node.js中的require()是否每次导入其他模块时都执行同一个文件?

如果是,我怎样才能在一个文件中包含一个数组,而在另一个 JS 文件中包含 append/update 值? 例如,我在一个文件中有一个数组,我正在从多个文件更新数组,我希望所有文件都只与更新后的数组交互。我怎样才能做到这一点?

模块已缓存,如果您再次加载它们,则会加载缓存副本。

https://nodejs.org/api/modules.html#modules_require_cache

Modules are cached in this object when they are required. By deleting a key value from this object, the next require will reload the module. This does not apply to native addons, for which reloading will result in an error.

Adding or replacing entries is also possible. This cache is checked before native modules and if a name matching a native module is added to the cache, no require call is going to receive the native module anymore. Use with care!

您可以使用https://www.npmjs.com/package/clear-module

const clearModule = require('clear-module');
const myArray = clearModule('./myArray'); // but you need load this everytime to get fresh copy of that array

相反,您可以从模块中公开一个函数来读取数组值,这样它就会始终获取新值。

myArray.js

const myArray = [1];

const get = () => {
  return myArray;
};

const update = (data) => {
  myArray.push(data);
};

exports.get = get;
exports.update = update;

index.js

const myArray = require('./myArray');

console.log(myArray.get()); // [1]
console.log(myArray.update(2)); // update the value
console.log(myArray.get()); // [1,2]

所以现在总是使用myArray.get()读取值并使用myArray.update(data)更新。