2013-03-27 38 views
37

让说,以后我需要一个模块,并做一些事情如下:如何在node.js中的“require”之后移除模块?

var b = require('./b.js'); 
--- do something with b --- 

然后我想带走模块B(即清理缓存)。我怎么能做到这一点?

原因是我想在不重新启动节点服务器的情况下动态加载/删除或更新模块。任何想法?

------- --------更多基于 上的建议,删除require.cache,它仍然无法正常工作......

what I did are few things: 
1) delete require.cache[require.resolve('./b.js')]; 
2) loop for every require.cache's children and remove any child who is b.js 
3) delete b 

然而,当我打电话给b,它仍然在那里!它仍然可以访问。除非我这样做:

b = {}; 

不知道这是否是一个好方法来处理。 ,因为如果以后我再次​​需要('./b.js'),而b.js已被修改。它会需要旧的缓存b.js(我试图删除)还是新的?

-----------更多发现--------------

好的。我做更多的测试和玩弄的代码..这里是我发现:

1) delete require.cache[] is essential. Only if it is deleted, 
then the next time I load a new b.js will take effect. 
2) looping through require.cache[] and delete any entry in the 
children with the full filename of b.js doesn't take any effect. i.e. 
u can delete or leave it. However, I'm unsure if there is any side 
effect. I think it is a good idea to keep it clean and delete it if 
there is no performance impact. 
3) of course, assign b={} doesn't really necessary, but i think it is 
useful to also keep it clean. 
+0

变量分配的'结果要求(“./ B”)'来不会被删除,'delete'操作只会让你需要一个文件第二次没有获得缓存版本,但是当你这样做的时候变量不会被神奇地更新。 – robertklep 2013-03-27 20:22:06

+0

是的..我的权利..这里是我发现...(见我的版本) – murvinlai 2013-03-27 21:55:07

+0

[node.js需要()缓存可能重复 - 可能无效?](http://stackoverflow.com/问题/ 9210542/node-js-require-cache-possible-to-invalidate) – Gajus 2014-11-12 18:55:04

回答

77

您可以使用它来删除它在缓存条目:

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

require.resolve()会找出./b.js的完整路径,用作缓存键。

+0

哦..让我试试。 所以完整路径将是module.filename? – murvinlai 2013-03-27 18:36:53

+1

试试吧。我认为这比删除更复杂。 做删除删除顶层缓存。但是,因为b.js是a.js的子项,所以它也作为a.js中的一个子项被缓存。所以,我想我也需要删除a.js的孩子 – murvinlai 2013-03-27 18:45:30

+2

请注意,您可能还需要删除'./b.js'所需的所有内容。根据你的用例,核选项可能是合适的:'_.each(_。keys(require.cache),function(key){delete require.cache [key];})' – mikermcneil 2015-05-27 12:28:07

0

我发现处理无效缓存最简单的方法实际上是重置暴露的缓存对象。从缓存中删除单个条目时,子依赖关系会变得有点麻烦。

require.cache = {};

+2

根据[this answer] (http://stackoverflow.com/a/23686122/1836935)更改缓存对象什么也不做,你需要删除它的键 – 2016-11-10 18:54:54

+1

这是错误的,只有删除键实际上删除缓存模块。 – lonewarrior556 2017-02-21 20:42:24