node.js - 清除需要缓存

标签 node.js caching

我试图从缓存中删除一个模块为 suggested here .

documentation我们读到:

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 的文件,其中包含一行:

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 = {} 时没有被清除。

最佳答案

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

关于node.js - 清除需要缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23685930/

相关文章:

node.js - 在 ionic + Electron (5.0.0) 桌面应用程序中需要 Node 模块

php - 单一缓存前端和后端

spring - 在 Spring Boot 应用程序启动时清除 Redis 缓存

node.js - 当挂载卷中的文件在主机上更改时,文件系统事件不会在 docker 容器中触发

node.js - 如何用 mocha 测试 node.js http 客户端?

node.js - Create-react-app 失败,出现错误 : node incompatible with css-loader

python - 对 `lru_cache` 修饰函数使用可变参数可能会出现什么困难?

caching - @Service 类中的 Spring Boot 缓存不起作用

python - 使用 Beaker 缓存和 SQLAlchemy

node.js - 调用助手(Handlebars)后无法访问数组元素