[Fixed] How do I cache files served with express.static in memory?


According to this question express.static reads files from the harddrive every time. I’d like to cache served files in memory, since they won’t be changing, there aren’t many and I have plenty of memory to do so.

So for code such as this:

// serve all static files from the /public folder
app.use(express.static(path.join(__dirname, 'public')))

// serve index.html for all routes
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'public/index.html'))

How do I make sure that express caches files served through express.static and res.sendFile in memory?


This usually isn’t worth the trouble, as the operating system will take care of this for you.

All modern operating systems will use unused RAM as “buffer cache” or “page cache”. Recently used file system data will be stored there, in RAM, so once a file has been loaded into memory any subsequent reads will be served from memory instead of actually being read from disk.

The advantage of relying on this is that the OS will automatically purge data from the buffer cache when there happens to be an increase in memory consumption from processes, thus not running the risk of memory-starving those processes (as you might have when you implement something in user space yourself).

Leave a Reply

(*) Required, Your email will not be published