Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing require cache

I am trying to delete a module from cache as suggested here.

In the documentation we read:

require.cache

  • Object

Modules are cached in this object when they are required. By deleting a key value from this object, the next require will reload the module.

So, I created a file named 1.js that contains a single line:

module.exports = 1;

Then I require it via node shell:

ionicabizau@laptop:~/Documents/test$ node
> require("./1")
1
> require.cache
{ '/home/ionicabizau/Documents/test/1.js': 
   { id: '/home/ionicabizau/Documents/test/1.js',
     exports: 1,
     parent: 
      { id: 'repl',
        exports: [Object],
        parent: undefined,
        filename: '/home/ionicabizau/Documents/test/repl',
        loaded: false,
        children: [Object],
        paths: [Object] },
     filename: '/home/ionicabizau/Documents/test/1.js',
     loaded: true,
     children: [],
     paths: 
      [ '/home/ionicabizau/Documents/test/node_modules',
        '/home/ionicabizau/Documents/node_modules',
        '/home/ionicabizau/node_modules',
        '/home/node_modules',
        '/node_modules' ] } }
# edited file to export 2 (module.exports = 2;)
> require.cache = {}
{}
> require.cache
{}
> require("./1") // supposed to return 2
1

So, why does require("./1") return 1 when my file contains module.exports = 2 and the cache is cleared?

Doing some debugging I saw that there is a Module._cache object that is not cleared when I do require.cache = {}.

like image 811
Ionică Bizău Avatar asked May 15 '14 18:05

Ionică Bizău


People also ask

What is require cache?

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.

Which object is used to manage the cache of required modules?

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.

How do I clear Nodejs cache?

Run: “npm cache clean –force” And if npm cache clean and npm cache verify . 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.

Is in scope which line of code will have an event emitter emitting a?

If EventEmitter is in scope, which of the following lines of code will have an event emitter emitting a change event? EventEmitter. emit('change'); EventEmitter.


1 Answers

require.cache is just an exposed cache object reference, this property is not used directly, so changing it does nothing. You need to iterate over keys and actually delete them.

like image 161
vkurchatkin Avatar answered Oct 22 '22 08:10

vkurchatkin