Skip to content

Instantly share code, notes, and snippets.

@joerx
Created Mar 20, 2015
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@FranckFreiburger FranckFreiburger commented Mar 6, 2017

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

@nezed nezed commented Feb 7, 2020

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

@lukasfarina

This comment has been minimized.

Copy link

@lukasfarina lukasfarina commented Jan 9, 2021

Thank you man!
helped me a lot :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment