2

Please find below a sample code in 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

I thought the delete would remove the reference to module and hence the last line should throw an error. But it does not. What could be the reason and what does delete cache really mean?

ssi
  • 23
  • 1
  • 4

2 Answers2

3

The cache doesn't know about it anymore but your var hello still has a reference to what was previously loaded.

The next time you call require('hello') it will load the module from the file. But, until you update the reference that var hello is holding, it will continue to point to the originally loaded module.

dc5
  • 12,341
  • 2
  • 35
  • 47
  • Thanks dc5 for the answer. I am getting what you mean by having reference to the module through var hello. I had this question after reading about unloading modules. Is there a way to unload module in nodejs and what does unload really mean? – ssi Aug 30 '13 at 05:03
  • Maybe the comments on the answer to this question will help: [unloading code/modules](http://stackoverflow.com/questions/6676612/unloading-code-modules). I'd say there is no way, through a single action to "unload" a module. You can drop it from the cache and reload it, but, as the referenced question indicates, it can get pretty interesting in anything but simple use cases. – dc5 Aug 30 '13 at 05:19
0

As you know, node would load a module once even if you require many times, Modules are cached after the first time they are loaded. If you delete it from cache, it will reload the module from filesystem to the cache the next time you require.

Isaiah
  • 432
  • 2
  • 6