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

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

问题描述

我正在尝试按照此处的建议从缓存中删除模块.

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

文档中,我们阅读了:

  • 对象

模块在需要时缓存在这个对象中.通过从此对象中删除一个键值,下一个 require 将重新加载模块.

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 只是一个暴露的缓存对象引用,这个属性不是直接使用的,所以改变它没有任何作用.您需要遍历键并实际删除它们.

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天全站免登陆