我试图从缓存中删除一个模块为 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/