Node.js › File System & File Processing

How would you implement a simple in-process file-based cache in Node.js, and what are the tradeoffs versus using Redis?

Advanced

Answer

A file-based cache writes computed results to disk (keyed by a hash of the input, often as the filename) and checks for an existing cached file before recomputing -- simple to implement with no external dependency, and durable across process restarts unlike an in-memory cache, but slower than Redis for high-frequency access due to filesystem I/O overhead, and doesn't naturally support features like automatic TTL expiration or being shared efficiently across multiple server instances the way Redis does.
const crypto = require('node:crypto');

async function getCached(key, computeFn) {
  const cacheFile = path.join('.cache', crypto.createHash('md5').update(key).digest('hex'));
  try {
    return JSON.parse(await fs.promises.readFile(cacheFile, 'utf-8'));
  } catch {
    const result = await computeFn();
    await fs.promises.writeFile(cacheFile, JSON.stringify(result));
    return result;
  }
}
Real-world example A build tool caches the results of expensive, deterministic compilation steps to disk keyed by a hash of the source file's content, letting subsequent builds skip recompiling unchanged files even after the build process itself has fully restarted, something a purely in-memory cache couldn't provide.

Common follow-ups: In what scenario is a file-based cache actually preferable to Redis despite Redis's speed advantage?;How would you implement TTL-style expiration for a file-based cache, given the filesystem has no built-in expiration concept?