【问题标题】:Clearing require cache清除需要缓存
【发布时间】:2014-07-04 08:30:51
【问题描述】:

我正在尝试从缓存中删除一个模块为suggested here

documentation我们读到:

require.cache

  • 对象

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

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

module.exports = 1;

然后我通过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

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

【问题讨论】:

    标签: node.js caching


    【解决方案1】:

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

    【讨论】:

    • 啊,现在我明白我的错误了。谢谢...!
    • Object.keys(require.cache).forEach(function(key) { delete require.cache[key] })
    • 有一个名为clear-require 的 NPM 包抽象了这个逻辑。
    • @Gajus“抽象了这个逻辑”??天哪,看在上帝的份上!
    猜你喜欢
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 2017-08-18
    • 2012-12-02
    • 2016-10-14
    • 1970-01-01
    • 2020-07-19
    相关资源
    最近更新 更多