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

标签 javascript node.js requirejs es6-modules javascript-import

这个问题在这里已经有了答案:





How requiring a module on entry point makes available on other modules on NodeJS?

(1 个回答)


去年关闭。




是否 require()在 JavaScript/Node.js 中每次导入其他模块时执行相同的文件?
如果是,我怎样才能在一个文件中有一个数组并从另一个 JS 文件中追加/更新其中的值?
例如,我在一个文件中有一个数组,我正在从多个文件更新数组,我希望它们都只与更新后的数组交互。我怎样才能做到这一点?

最佳答案

模块被缓存,如果您再次加载它们,则会加载缓存的副本。
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)来更新。

关于javascript - javascript/nodejs 中的 require 是否每次在另一个模块中导入时都会执行相同的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66647911/

相关文章:

javascript - 在 RequireJS require 函数中处理先决条件加载失败

javascript - 未捕获的类型错误 : Cannot read property 'EventAggregator' of undefined (Backbone, Marionette,RequireJS)

javascript - OnClick Dropdown 在 FireFox 中有效,但在 Chrome 或 IE 中无效?

javascript - 如何在Javascript中点击按钮后显示div?

javascript - 如何以大写形式显示列表中的项目?

javascript - 风 sails js : Setting response method based on request parameter

javascript - 无法读取未定义的属性 'isArray'

javascript - 使用 JavaScript 异步加载图像

javascript - 尝试使用 axios 从 Reactjs 组件发送数据到 Express 应用程序

javascript - 如何检查两个数组是否包含相同的值,即使它们位于不同的索引中?