1

I was reading some of the answers at Stack Overflow about lazy loading and manual unloading of modules in NodeJS, one of the answers quoted

Node is single threaded so the memory footprint of loading a module is not per-connection, it's per-process. Loading a module is a one-off to get it into memory.

Which is a fair enough explanation, but then there is a question that is there some point of time when the old unused modules (that were earlier required and are no longer used in execution) cleared from cache? How does the Garbage Collector works in this case?

UPDATE:

This answer shows how to manually remove a module from cache, which also indicates that module caching might be different from regular in-memory objects

var name = require.resolve('moduleName');
delete require.cache[name];
Community
  • 1
  • 1
Ammar Hasan
  • 2,436
  • 16
  • 22
  • 1
    *"...which also indicates that module caching might be different from regular in-memory objects"* No, not at all: It just shows deleting a property from an object (`cache`). If that property was referring to an object (a module), and it was the only reference to it, then the object would be eligible for garbage collection. Not special at all, standard object stuff. – T.J. Crowder Mar 05 '16 at 18:10
  • Note that there's nothing in the modules documentation about `require.cache`, which means that even if the above worked in (say) v5.7.1, you'd have no guarantee at all it wouldn't break in v5.7.2. Undocumented things are subject to change. – T.J. Crowder Mar 05 '16 at 18:12

1 Answers1

1

Node's documentation on modules says they're cached (doesn't seem different in the v5 docs either), and doesn't suggest any mechanism by which the cache releases its reference to the module. As long as there is a reference to the module (e.g., in the caching mechanism), it will be retained in memory, like any other JavaScript object.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875