Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Node's require cache garbage collected?

Tags:

node.js

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

like image 716
Bruno Brant Avatar asked Jun 03 '16 17:06

Bruno Brant


People also ask

Does NodeJS cache require?

Per the node documentation, modules are cached after the first time they are loaded (loaded is synonymous with 'required'). They are placed in the require. cache . This means that every future require for a previously loaded module throughout a program will load the same object that was loaded by the first require.

Is NodeJS garbage collected?

Luckily for you, Node. js comes with a garbage collector, and you don't need to manually manage memory allocation.

Are node modules cache?

Since required modules are cached in Node. js, it means that multiple modules could be using the same cache at the same time.

When should I use NodeJS cache?

Node cache is faster to store and retrieve data with a TTL (Time To Live). Things to consider before choosing the right Caching technique: Security risks for storing and retaining the data in the cache. Data object serialization is really required for storing the data.


1 Answers

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.

like image 104
jfriend00 Avatar answered Oct 20 '22 10:10

jfriend00