node.js require() cache - possible to invalidate?

后端 未结 17 1661
我寻月下人不归
我寻月下人不归 2020-11-22 06:52

From the node.js documentation:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require(\'

17条回答
  •  悲&欢浪女
    2020-11-22 07:32

    There's a Simple Module for that (with tests)

    We had this exact issue while testing our code (delete cached modules so they can be re-required in a fresh state) so we reviewed all the suggestions of people on the various StackOverflow Questions & Answers and put together a simple node.js module (with tests):

    https://www.npmjs.com/package/decache

    As you would expect, works for both published npm packages and locally defined modules. Windows, Mac, Linux, etc.

    How? (usage)

    Usage is pretty simple:

    install

    Install the module from npm:

    npm install decache --save-dev

    Use it in your code:

    // require the decache module:
    const decache = require('decache');
    
    // require a module that you wrote"
    let mymod = require('./mymodule.js');
    
    // use your module the way you need to:
    console.log(mymod.count()); // 0   (the initial state for our counter is zero)
    console.log(mymod.incrementRunCount()); // 1
    
    // delete the cached module:
    decache('./mymodule.js');
    
    //
    mymod = require('./mymodule.js'); // fresh start
    console.log(mymod.count()); // 0   (back to initial state ... zero)
    

    If you have any questions or need more examples, please create a GitHub issue: https://github.com/dwyl/decache/issues

提交回复
热议问题