清除要求缓存 [英] Clearing require cache

查看:72
本文介绍了清除要求缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图按建议在此处的方式从缓存中删除模块.

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

文档中,我们读到:

require.cache

  • 对象

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.

因此,我创建了一个名为1.js的文件,其中包含一行:

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

module.exports = 1;

然后我需要通过node shell:

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

那么,当我的文件包含module.exports = 2并清除了缓存时,为什么require("./1")返回1呢?

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

进行一些调试,我发现有一个Module._cache对象在执行require.cache = {}时没有清除.

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

推荐答案

require.cache只是公开的缓存对象引用,不会直接使用此属性,因此更改它不会执行任何操作.您需要遍历键,然后实际上delete它们.

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.

这篇关于清除要求缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆