7

NodeJS require function, that loads modules, has a "cache" (which is a object).

Entries is this cache are garbage collected once I'm no longer using the module? (resulting in loading from disk if used again)

I think the answer is "no", but I didn't found any references on the web

Bruno Brant
  • 8,226
  • 7
  • 45
  • 90

1 Answers1

8

Entries is this cache are garbage collected once I'm no longer using the module?

No. Modules loaded with require() are cached indefinitely whether you are done using them or not.

Memory for Javascript variables/objects that is used by the module is garbage collected subject to all the normal rules of garbage collection (when there is no live code that still has a reference to the variable/object). But, the module cache keeps a reference to the loaded module itself so the code or any module level variables are not garbage collected unless a module is manually removed from the cache.

Here's a link to the node.js doc on the topic.

Caching

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

If you want to manually remove a module from the cache, that is described here:

unloading code/modules

Though, this will allow all module-level variables to be garbage collected, given the way node.js is structured I don't think it will actually unload the code from memory.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979