2

请在下面找到 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

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

4

2 回答 2

3

缓存不再知道它,但您的 varhello仍然具有对先前加载的内容的引用。

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

于 2013-08-30T04:08:47.493 回答
0

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

于 2013-08-30T04:25:11.317 回答