讓說,以後我需要一個模塊,並做一些事情如下:如何在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