Kirk Ouimet
Kirk Ouimet

Reputation: 28364

Is it smart to keep static files in memory in node js?

When serving static files in Node I am simply using fs.readFile and then throwing the data onto the response content.

I am tempted to store the results of fs.readFile in a variable and then skip using fs.readFile when the file is requested a second time and just write the content out from the variable in memory.

My questions:

  1. Are there any issues I could run into with this approach? Is there a better way?
  2. (a high level overview) How do servers like nginx and Apache cache files to serve to users?

Upvotes: 2

Views: 1023

Answers (1)

zerkms
zerkms

Reputation: 254944

Are there any issues I could run into with this approach? Is there a better way?

Yep, you can run out of memory. You can keep in cache only what is hot.

How do servers like nginx and Apache cache files to serve to users?

They keep it in memory indeed but additionally they implement some LRU (or LRU-alike) strategy to invalidate caches.

References:

Upvotes: 2

Related Questions