2013-03-27 40 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