Bird
Raised Fist0
Node.jsframework~5 mins

Why caching matters in Node.js

Choose your learning style10 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.

Practice

(1/5)
1. Why is caching important in Node.js applications?
easy
A. It saves time by reusing data instead of fetching it repeatedly.
B. It increases the size of the application code.
C. It makes the application slower by adding extra steps.
D. It removes the need for any database connections.

Solution

  1. Step 1: Understand caching purpose

    Caching stores data temporarily to avoid repeated fetching.
  2. Step 2: Identify benefit in Node.js

    Reusing cached data saves time and reduces resource use.
  3. Final Answer:

    It saves time by reusing data instead of fetching it repeatedly. -> Option A
  4. Quick Check:

    Caching improves speed = A [OK]
Hint: Caching means reusing data to save time [OK]
Common Mistakes:
  • Thinking caching increases app size
  • Believing caching slows down the app
  • Assuming caching removes database needs
2. Which of the following is the correct way to create a simple cache using Map in Node.js?
easy
A. const cache = new map();
B. const cache = new Map();
C. const cache = Map();
D. const cache = new Cache();

Solution

  1. Step 1: Recall Map creation syntax

    Map is a built-in object and must be created with 'new Map()'.
  2. Step 2: Check each option

    Only 'const cache = new Map();' uses correct capitalization and syntax.
  3. Final Answer:

    const cache = new Map(); -> Option B
  4. Quick Check:

    Correct Map syntax = C [OK]
Hint: Use 'new Map()' with capital M and parentheses [OK]
Common Mistakes:
  • Omitting 'new' keyword
  • Using lowercase 'map' instead of 'Map'
  • Trying to use 'Cache' which is undefined
3. Consider this Node.js code snippet using a cache:
const cache = new Map();
function getData(key) {
  if (cache.has(key)) {
    return cache.get(key);
  }
  const value = key * 2;
  cache.set(key, value);
  return value;
}
console.log(getData(5));
console.log(getData(5));
What will be printed to the console?
medium
A. 10 and 10
B. 10 and undefined
C. NaN and NaN
D. 5 and 5

Solution

  1. Step 1: Analyze first call getData(5)

    Cache is empty, so value = 5 * 2 = 10 is stored and returned.
  2. Step 2: Analyze second call getData(5)

    Cache has key 5, so cached value 10 is returned again.
  3. Final Answer:

    10 and 10 -> Option A
  4. Quick Check:

    Cache returns stored value = D [OK]
Hint: Cached value returns same result on repeated calls [OK]
Common Mistakes:
  • Assuming second call returns undefined
  • Confusing key and value calculations
  • Ignoring cache.has() check
4. This code tries to cache results but has a bug:
const cache = new Map();
function fetchData(key) {
  if (cache[key]) {
    return cache[key];
  }
  const result = key + 100;
  cache[key] = result;
  return result;
}
What is the main problem with this caching approach?
medium
A. Not converting key to string before caching.
B. Using '+' operator instead of '*' for calculation.
C. Missing return statement inside the if block.
D. Using Map but accessing it like a plain object with bracket notation.

Solution

  1. Step 1: Identify Map usage

    cache is a Map, but code uses cache[key] which is object syntax, not Map methods.
  2. Step 2: Correct Map access

    Map requires cache.has(key) and cache.get(key) to check and retrieve values.
  3. Final Answer:

    Using Map but accessing it like a plain object with bracket notation. -> Option D
  4. Quick Check:

    Map needs .get()/.has(), not bracket [] = B [OK]
Hint: Use Map methods, not bracket notation, for Map objects [OK]
Common Mistakes:
  • Treating Map like a plain object
  • Forgetting to use cache.has()
  • Assuming keys auto-convert to strings
5. You want to cache API responses in Node.js but only for data that changes slowly. Which approach best balances freshness and speed?
hard
A. Never cache data and always fetch fresh data.
B. Cache data forever without expiration to maximize speed.
C. Cache data with a time-to-live (TTL) that expires after a set period.
D. Cache only error responses to avoid retries.

Solution

  1. Step 1: Understand caching for slowly changing data

    Data that changes slowly benefits from caching but needs periodic refresh.
  2. Step 2: Evaluate caching strategies

    Using TTL allows cache to expire and refresh, balancing speed and freshness.
  3. Final Answer:

    Cache data with a time-to-live (TTL) that expires after a set period. -> Option C
  4. Quick Check:

    TTL caching balances freshness and speed = A [OK]
Hint: Use TTL to refresh cache for slowly changing data [OK]
Common Mistakes:
  • Caching forever causes stale data
  • Not caching wastes time on repeated fetches
  • Caching only errors misses main data benefits
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard