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

后端 未结 5 1957
感动是毒
感动是毒 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]
          }
        }
    
    0 讨论(0)
  • 2020-11-29 00:46

    You can use this to delete its entry in the cache:

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

    require.resolve() will figure out the full path of ./b.js, which is used as a cache key.

    0 讨论(0)
  • 2020-11-29 00:48

    I found this useful for client side applications. I wanted to import code as I needed it and then garbage collect it when I was done. This seems to work. I'm not sure about the cache, but it should get garbage collected once there is no more reference to module and CONTAINER.sayHello has been deleted.

    /* my-module.js */
    
    function sayHello { console.log("hello"); }
    
    export { sayHello };
    
    /* somewhere-else.js */
    
    const CONTAINER = {};
    
    import("my-module.js").then(module => {
    
      CONTAINER.sayHello = module.sayHello;
    
      CONTAINER.sayHello(); // hello
    
      delete CONTAINER.sayHello;
    
      console.log(CONTAINER.sayHello); // undefined
    
    });
    
    0 讨论(0)
  • 2020-11-29 00:59

    I have found the easiest way to handle invalidating the cache is actually to reset the exposed cache object. When deleting individual entries from the cache, the child dependencies become a bit troublesome to iterate through.

    require.cache = {};

    0 讨论(0)
  • 2020-11-29 01:03

    Spent some time trying to clear cache in Jest tests for Vuex store with no luck. Seems like Jest has its own mechanism that doesn't need manual call to delete require.cache.

    beforeEach(() => {
      jest.resetModules();
    });
    

    And tests:

    let store;
    
    it("1", () => {
       process.env.something = true;
       store = require("@/src/store.index");
    });
    
    it("2", () => {
       process.env.something = false;
       store = require("@/src/store.index");
    });
    

    Both stores will be different modules.

    0 讨论(0)
提交回复
热议问题