Skip to content

Instantly share code, notes, and snippets.

@joerx
Created March 20, 2015 00:04
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joerx/3296d972735adc5b4ec1 to your computer and use it in GitHub Desktop.
Save joerx/3296d972735adc5b4ec1 to your computer and use it in GitHub Desktop.
Clear require cache in Node.js
//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
module.exports.counter = 0;
@FranckFreiburger
Copy link

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
module.invalidable = true;

var count = 0;
exports.count = function() {

	return count++;
}
main module ./index.js
require('module-invalidate');

var myModule = require('./myModule.js');

console.log( myModule.count() ); // 0
console.log( myModule.count() ); // 1

module.constructor.invalidateByExports(myModule);

console.log( myModule.count() ); // 0
console.log( myModule.count() ); // 1

@nezed
Copy link

nezed commented Sep 10, 2019

@FranckFreiburger unfortunately you library does not invalidates any modules in node v12.6.0.

Solution described above still works great!

@flyon
Copy link

flyon commented Feb 7, 2020

@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.

@nezed
Copy link

nezed commented Feb 7, 2020

Its just better to use Jest in many cases https://jestjs.io/docs/en/jest-object#mock-modules

@lukasfarina
Copy link

Thank you man!
helped me a lot :D

@bjpirt
Copy link

bjpirt commented Jan 9, 2023

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