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

后端 未结 17 1917
我寻月下人不归
我寻月下人不归 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:43

    I made a small module to delete module from the cache after loading. This forces reevaluation of the module next time it is required. See https://github.com/bahmutov/require-and-forget

    // random.js
    module.exports = Math.random()
    const forget = require('require-and-forget')
    const r1 = forget('./random')
    const r2 = forget('./random')
    // r1 and r2 will be different
    // "random.js" will not be stored in the require.cache
    

    PS: you can also put "self-destruct" into the module itself. See https://github.com/bahmutov/unload-me

    PSS: more tricks with Node require in my https://glebbahmutov.com/blog/hacking-node-require/

提交回复
热议问题