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


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('foo') will get exactly the same object returned, if it would resolve to the same file.

Is there a way to invalidate this cache? i.e. for unit testing, I'd like each test to be working on a fresh object.

2/9/2012 12:07:16 PM

Accepted Answer

You can always safely delete an entry in require.cache without a problem, even when there are circular dependencies. Because when you delete, you just delete a reference to the cached module object, not the module object itself, the module object will not be GCed because in case of circular dependencies, there is still a object referencing this module object.

Suppose you have:

script a.js:

var b=require('./b.js').b;
exports.a='a from a.js';

and script b.js:

var a=require('./a.js').a;
exports.b='b from b.js';

when you do:

var a=require('./a.js')
var b=require('./b.js')

you will get:

> a
{ a: 'a from a.js', b: 'b from b.js' }
> b
{ b: 'b from b.js', a: undefined }

now if you edit your b.js:

var a=require('./a.js').a;
exports.b='b from b.js. changed value';

and do:

delete require.cache[require.resolve('./b.js')]

you will get:

> a
{ a: 'a from a.js', b: 'b from b.js' }
> b
{ b: 'b from b.js. changed value',
  a: 'a from a.js' }
5/30/2018 1:40:27 PM

If you always want to reload your module, you could add this function:

function requireUncached(module){
    delete require.cache[require.resolve(module)]
    return require(module)

and then use requireUncached('./myModule') instead of require.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow