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.
Per the node documentation, modules are cached after the first time they are loaded (loaded is synonymous with 'required'). They are placed in the require. cache . This means that every future require for a previously loaded module throughout a program will load the same object that was loaded by the first require.
Module. _load performs the loading of new modules and manages the cache. On a file loading request, it will first check the file in cache. If module is not found in the cache, this will create a new base module instance for the required file.
Run: “npm cache clean –force” are both not working and you still can't clear the cache, you can force clear the cache by running: npm cache clean --force or npm cache clean -f . This will force delete the npm cache on your computer.
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'; exports.b=b;
and script b.js:
var a=require('./a.js').a; exports.b='b from b.js'; exports.a=a;
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'; exports.a=a;
and do:
delete require.cache[require.resolve('./b.js')] b=require('./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' }
===
The above is valid if directly running node.js. However, if using tools that have their own module caching system, such as jest, the correct statement would be:
jest.resetModules();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With