0
0
Node.jsframework~5 mins

In-memory caching patterns in Node.js

Choose your learning style9 modes available
Introduction

In-memory caching stores data temporarily inside your app's memory. It helps your app get data faster without asking a database every time.

When you want to speed up repeated data requests in your app.
When your app needs quick access to data that doesn't change often.
When you want to reduce load on your database or external services.
When you want to store session or user info temporarily during a user visit.
Syntax
Node.js
const cache = new Map();

// Save data
cache.set(key, value);

// Get data
const value = cache.get(key);

// Check if key exists
const hasKey = cache.has(key);

// Remove data
cache.delete(key);

// Clear all cache
cache.clear();

Map is a built-in JavaScript object good for simple in-memory caching.

You can use any string or object as a key in Map.

Examples
Store and get a user object by key 'user_1'.
Node.js
cache.set('user_1', { name: 'Alice', age: 25 });
const user = cache.get('user_1');
Check if 'settings' data is already cached before using it.
Node.js
if (cache.has('settings')) {
  console.log('Settings found in cache');
}
Remove 'temp_data' from cache when no longer needed.
Node.js
cache.delete('temp_data');
Clear all cached data, useful when resetting app state.
Node.js
cache.clear();
Sample Program

This Node.js server caches the current time when you visit /time. The first request stores the time, and later requests return the cached time quickly. Visiting /clear clears the cache.

Node.js
import http from 'node:http';

const cache = new Map();

const server = http.createServer((req, res) => {
  const url = req.url || '';

  if (url === '/time') {
    if (cache.has('time')) {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end(`Cached time: ${cache.get('time')}`);
    } else {
      const now = new Date().toISOString();
      cache.set('time', now);
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end(`New time cached: ${now}`);
    }
  } else if (url === '/clear') {
    cache.clear();
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Cache cleared');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not found');
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});
OutputSuccess
Important Notes

In-memory cache is fast but resets when the app restarts.

Use cache carefully to avoid stale data by adding expiration if needed.

For bigger apps, consider dedicated caching tools like Redis.

Summary

In-memory caching stores data inside your app for quick reuse.

Use JavaScript's Map for simple cache storage and retrieval.

Remember cache clears on app restart and may need expiration logic.