Created
March 20, 2015 00:04
-
-
Save joerx/3296d972735adc5b4ec1 to your computer and use it in GitHub Desktop.
Clear require cache in Node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//based on http://stackoverflow.com/questions/9210542/node-js-require-cache-possible-to-invalidate | |
function clearRequireCache() { | |
Object.keys(require.cache).forEach(function(key) { | |
delete require.cache[key]; | |
}); | |
} | |
var myModule1 = require('./my-module'); | |
console.log(myModule1.counter); // 0 | |
myModule1.counter += 1; | |
console.log(myModule1.counter); // 1 | |
var myModule2 = require('./my-module'); | |
console.log(myModule2.counter); // 1 | |
clearRequireCache(); | |
// since cache is cleared, counter will be 0 on the new instance | |
myModule1 = require('./my-module'); | |
console.log(myModule1.counter); // 0 | |
// however, old 'instance' still maintains state | |
console.log(myModule2.counter); // 1 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports.counter = 0; |
@FranckFreiburger unfortunately you library does not invalidates any modules in node v12.6.0
.
Solution described above still works great!
@FranckFreiburger same here. I like the idea of your library - removing all dependants - but my module doesnt get reloaded so it must be missing something.
Its just better to use Jest in many cases https://jestjs.io/docs/en/jest-object#mock-modules
Thank you man!
helped me a lot :D
Specifically; jest.resetModules() is your friend here: https://jestjs.io/docs/jest-object#jestresetmodules
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello,
have a look at my module-invalidate module that allows you to invalidate a module and make it automatically reloaded on further access.
Example:
module
./myModule.js
main module
./index.js