如何在node.js中的“require”之后移除模块?
比方说,我需要一个模块后,做一些事情如下:
var b = require('./b.js'); --- do something with b ---
然后我想拿走模块b(即清理caching)。 我怎么能做到这一点?
原因是我想在不重新启动节点服务器的情况下dynamic加载/删除或更新模块。 任何想法?
——-更多——–根据build议删除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已被修改。 它会需要旧的cachingb.js(我试图删除),还是新的?
———–更多发现————–
好。 我做更多的testing,并与代码玩…这里是我发现:
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. ie 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.
您可以使用它来删除caching中的条目:
delete require.cache[require.resolve('./b.js')]
require.resolve()
将找出用作caching键的./b.js
的完整path。
我发现处理无效caching最简单的方法实际上是重置暴露的caching对象。 当从caching中删除单个条目时,子依赖关系会变得有点麻烦迭代。
require.cache = {};