node.js 清除需要缓存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23685930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:20:54  来源:igfitidea点击:

Clearing require cache

node.jscaching

提问by Ionic? Biz?u

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

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

In the documentationwe 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.

需要缓存

  • 目的

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

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

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

module.exports = 1;

Then I require it via nodeshell:

然后我通过nodeshell要求它:

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 1when my file contains module.exports = 2and the cache is cleared?

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

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

做一些调试我看到有一个Module._cache对象在我做的时候没有被清除require.cache = {}

回答by vkurchatkin

require.cacheis 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 deletethem.

require.cache只是一个暴露的缓存对象引用,这个属性不是直接使用的,所以改变它没有任何作用。您需要迭代键,实际上是delete它们。