node.js require() 缓存 - 可能失效? [英] node.js require() cache - possible to invalidate?

查看:42
本文介绍了node.js require() 缓存 - 可能失效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 node.js 文档:

From the node.js documentation:

模块在第一次加载后被缓存.这意味着(除其他外)每次调用 require('foo') 都会返回完全相同的对象,如果它解析为同一个文件.

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

有没有办法使这个缓存失效?即对于单元测试,我希望每个测试都在一个新对象上工作.

Is there a way to invalidate this cache? i.e. for unit testing, I'd like each test to be working on a fresh object.

推荐答案

您始终可以安全地删除 require.cache 中的条目而不会出现问题,即使存在循环依赖项也是如此.因为当你删除的时候,你只是删除了一个对缓存模块对象的引用,而不是模块对象本身,模块对象不会被GCed,因为在循环依赖的情况下,仍然有一个对象引用这个模块对象.

You can always safely delete an entry in require.cache without a problem, even when there are circular dependencies. Because when you delete, you just delete a reference to the cached module object, not the module object itself, the module object will not be GCed because in case of circular dependencies, there is still a object referencing this module object.

假设你有:

脚本 a.js:

var b=require('./b.js').b;
exports.a='a from a.js';
exports.b=b;

脚本b.js:

var a=require('./a.js').a;
exports.b='b from b.js';
exports.a=a;

当你这样做时:

var a=require('./a.js')
var b=require('./b.js')

你会得到:

> a
{ a: 'a from a.js', b: 'b from b.js' }
> b
{ b: 'b from b.js', a: undefined }

现在如果你编辑你的 b.js:

now if you edit your b.js:

var a=require('./a.js').a;
exports.b='b from b.js. changed value';
exports.a=a;

然后做:

delete require.cache[require.resolve('./b.js')]
b=require('./b.js')

你会得到:

> a
{ a: 'a from a.js', b: 'b from b.js' }
> b
{ b: 'b from b.js. changed value',
  a: 'a from a.js' }

===

以上在直接运行node.js时有效.但是,如果使用具有自己的模块缓存系统的工具,例如 jest,则正确的说法是:

The above is valid if directly running node.js. However, if using tools that have their own module caching system, such as jest, the correct statement would be:

jest.resetModules();

这篇关于node.js require() 缓存 - 可能失效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆