删除缓存在Nodej中意味着什么

时间:2013-08-30 03:57:48

标签: node.js

请在下面找到nodejs中的示例代码:

var hello_file = require.resolve('hello')

var hello = require('hello')
console.log(m.hello()); // there is a method hello in module hello.js

delete require.cache[hello_file]
console.log(m.hello()); // it still works

我认为删除会删除对模块的引用,因此最后一行应该抛出错误。但事实并非如此。可能是什么原因以及删除缓存真正意味着什么?

2 个答案:

答案 0 :(得分:3)

缓存不再知道它了,但你的var hello仍然引用了之前加载的内容。

下次调用require('hello')时,它将从文件中加载模块。但是,在更新var hello所持有的引用之前,它将继续指向最初加载的模块。

答案 1 :(得分:0)

如您所知,即使您需要多次,节点也会加载一次模块,模块在第一次加载后会被缓存。如果从缓存中删除它,则会在下次需要时将模块从文件系统重新加载到缓存中。