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

问题描述

从node.js文档中:

From the node.js documentation:

是否有一种方法可以使此缓存无效?也就是说,对于单元测试,我希望每个测试都可以在一个新对象上进行.

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中的条目.因为在删除时,您只删除对缓存的模块对象的引用,而不是对模块对象本身的引用,所以不会对GC对象进行GC,因为在循环依赖的情况下,仍然有一个对象引用此模块对象.

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 require()缓存-可能无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 06:41
查看更多