たとえば、モジュールが必要で、次のようにするとします。
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 (削除しようとしました) が必要ですか、それとも新しい 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.