比方说,在我需要一个模块并执行以下操作之后:
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.