How to remove module after “require” in node.js?

后端 未结 5 1959
感动是毒
感动是毒 2020-11-29 00:27

Let say, after I require a module and do something as below:

var b = require(\'./b.js\');
--- do something with b ---

Then I want to take a

5条回答
  •  春和景丽
    2020-11-29 00:43

    One of the easiest ways (although not the best in terms of performance as even unrelated module's caches get cleared) would be to simply purge every module in the cache

    Note that clearing the cache for *.node files (native modules) might cause undefined behaviour and therefore is not supported (https://github.com/nodejs/node/commit/5c14d695d2c1f924cf06af6ae896027569993a5c), so there needs to be an if statement to ensure those don't get removed from the cache, too.

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

提交回复
热议问题