让说,以后我需要一个模块,并做一些事情如下:如何在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.
变量分配的'结果要求(“./ B”)'来不会被删除,'delete'操作只会让你需要一个文件第二次没有获得缓存版本,但是当你这样做的时候变量不会被神奇地更新。 – robertklep 2013-03-27 20:22:06
是的..我的权利..这里是我发现...(见我的版本) – murvinlai 2013-03-27 21:55:07
[node.js需要()缓存可能重复 - 可能无效?](http://stackoverflow.com/问题/ 9210542/node-js-require-cache-possible-to-invalidate) – Gajus 2014-11-12 18:55:04