سؤال

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 = {}.

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

for (var i in require.cache) { delete require.cache[i] }

If you need to filter specific files, i could be filtered with specific Regular Expression or rules at your customization.

for (var i in require.cache) { if (i.startsWith('src/cache/') )delete require.cache[i] }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top