web-dev-qa-db-ja.com

node.jsで「必須」の後にモジュールを削除するにはどうすればよいですか?

私がモジュールを必要とし、以下のように何かをした後、言ってみましょう:

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(削除しようとしました)または新しいものが必要ですか?

-----------その他の調査結果--------------

oK。私はコードをさらにテストして遊んでいます..私が見つけたものは次のとおりです:

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.
50
murvinlai

これを使用して、キャッシュ内のエントリを削除できます。

_delete require.cache[require.resolve('./b.js')]
_

require.resolve()は、キャッシュキーとして使用される_./b.js_のフルパスを計算します。

103
robertklep

最も簡単な方法の1つは、関連性のないモジュールのキャッシュもクリアされるため、パフォーマンスの点では最適ではありませんが、キャッシュ内のすべてのモジュールを単純にパージすることです

*.nodeファイル(ネイティブモジュール)のキャッシュをクリアすると、未定義の動作が発生する可能性があるため、サポートされないことに注意してください( https://github.com/nodejs/node/commit/5c14d695d2c1f924cf06af6ae896027569993a5c )、そのため、ifステートメントを使用して、それらがキャッシュから削除されないようにする必要があります。

    for (const path in require.cache) {
      if (path.endsWith('.js')) { // only clear *.js, not *.node
        delete require.cache[path]
      }
    }
3
mkg20001

キャッシュの無効化を処理する最も簡単な方法は、実際に公開されたキャッシュオブジェクトをリセットすることです。キャッシュから個々のエントリを削除する場合、子の依存関係を反復するのが少し面倒になります。

require.cache = {};
1
Jason Graves