Course contentsShow
← Node.js
Lesson 379 of 1,9804. I/O and File System OperationsFree lesson

Caching Strategies for Local Files

Design an in-memory file cache to reduce disk I/O for frequently accessed configurations.

In this lesson, you will learn how to design a simple in-memory cache to store configuration data, minimizing expensive disk I/O operations.

Why Cache Files?

Every time your application calls fs.readFileSync or fs.readFile, the operating system must perform a system call, traverse the file system, and wait for the disk hardware to retrieve the data. While fast, disk I/O is orders of magnitude slower than accessing data already loaded into your application's RAM. If you have a configuration file that is read repeatedly (like database credentials or feature flags), querying the disk every time creates unnecessary latency.

Designing the In-Memory Store

The pattern here is straightforward: "check the cache first, fallback to disk if missing." By storing the file contents in a standard JavaScript object or Map after the first read, you transform a multi-millisecond disk operation into a sub-microsecond memory lookup.

const fs = require('fs');

const configCache = new Map();

function getCachedConfig(filePath) {
  // 1. Check if we already have the data in RAM
  if (configCache.has(filePath)) {
    return configCache.get(filePath);
  }

  // 2. If not, perform the slow disk operation
  console.log('Reading from disk...');
  const data = fs.readFileSync(filePath, 'utf-8');

  // 3. Store the result for future requests
  configCache.set(filePath, data);
  return data;
}

Important Considerations

When implementing this, remember that your cache is now "stale" if the underlying file on the disk changes. If your application needs to handle dynamic file updates, you must implement an invalidation strategy—such as clearing the configCache entry when an fs.watch event detects a change, or using a time-to-live (TTL) mechanism to periodically refresh the data.

Because this cache resides in your process memory, be mindful of the total size of files you are caching; storing massive files in memory can lead to excessive garbage collection pressure or even OutOfMemory errors. Always cache only what is frequently needed and keep the payloads small.

Key Takeaway: By intercepting read requests with an in-memory Map, you eliminate redundant disk I/O and significantly accelerate access to static configuration files.