1

I read that when you require a file, node.js reads the file from disk only the first time, and after that caches it.

When are items removed from the cache ? If I require 1000's of different files (each only once, within a methods scope), then can my server run out of memory (because of the cache), or does the cache have a fixed size, after which it removes items from the cache ?

function foo(var bar){

    var shoe;
    if (bar === "blue"){
        shoe = require("./somefile.js");
    }else if (bar === "red"){
        shoe = require ("./someotherfile.js"){
    } //.....etc m

    //Do something with shoe etc...

}

I ask because, I have many different files stored as JSON, and using require is more convenient than using fs to create the object.

Rahul Iyer
  • 19,924
  • 21
  • 96
  • 190
  • Once a piece of Javascript is loaded into memory, it stays in memory for duration of that node.js process. It never goes away. The cache is just a small reference to the module that was previously loaded. If you are indeed doing `require()` on thousands of files, that will take more and more memory, but not because of the cache - but because of the additional code you are loading each time you `require()` a module that hasn't previously been loaded. The cache prevents it from getting loaded again if you request the same module that has already been loaded. – jfriend00 Oct 31 '14 at 08:40
  • @jfriend00 So are you saying that the cache will keep growing indefinitely (until I run out of memory). But I assume I can explicitly delete the item from the cache? – Rahul Iyer Oct 31 '14 at 08:46
  • The cache is a very small amount of memory. It just retains some metadata about each loaded module. The lion's share of the memory is used by the module itself. I don't know of any way to "unrequire" a module or to modify the cache. I don't know why you'd focus on the cache at all. That would not be your issue if you were running low on memory. – jfriend00 Oct 31 '14 at 17:21
  • I would have to unload the module if If I was running low on memory. – Rahul Iyer Nov 01 '14 at 02:20
  • 1
    Related answers: http://stackoverflow.com/questions/6676612/unloading-code-modules and http://stackoverflow.com/questions/17682104/release-required-module-from-node-js and https://groups.google.com/forum/#!topic/nodejs/I26CN95d_JM – jfriend00 Nov 01 '14 at 02:23

0 Answers0