0
0
Node.jsframework~5 mins

Why caching matters in Node.js

Choose your learning style9 modes available
Introduction

Caching helps your app work faster by saving data so it doesn't have to get it again. This makes users happy because things load quickly.

When your app fetches the same data many times, like user profiles or product info.
When you want to reduce slow calls to a database or external service.
When you want to handle many users at once without slowing down.
When you want to save money by using fewer resources like servers or bandwidth.
Syntax
Node.js
const cache = new Map();

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

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

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

Use a simple Map for small, in-memory caching in Node.js.

Keys can be strings or objects, values can be any data.

Examples
Store and retrieve a user object by key.
Node.js
cache.set('user_1', { name: 'Alice', age: 30 });
const user = cache.get('user_1');
Check if data is already cached before using it.
Node.js
if (cache.has('settings')) {
  console.log('Settings found in cache');
} else {
  console.log('Settings not cached yet');
}
Sample Program

This simple Node.js server caches responses by URL. The first request waits 1 second and caches the data. Later requests return the cached data instantly.

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

const cache = new Map();

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

  if (cache.has(url)) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end(`Cached response: ${cache.get(url)}`);
    return;
  }

  // Simulate slow data fetch
  setTimeout(() => {
    const data = `Data for ${url}`;
    cache.set(url, data);
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end(`Fresh response: ${data}`);
  }, 1000);
});

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

Caching can use memory, so be careful with large data or many entries.

Cached data might get outdated; plan how and when to refresh it.

Summary

Caching saves time by reusing data instead of fetching it again.

Use caching when data is requested often and changes slowly.

Simple caches in Node.js can use Map for quick storage and lookup.