0
0
Node.jsframework~30 mins

Why caching matters in Node.js - See It in Action

Choose your learning style9 modes available
Why caching matters
📖 Scenario: You are building a simple Node.js server that fetches user data from a slow database. To make the server faster and reduce repeated database calls, you will add caching.
🎯 Goal: Build a Node.js server that caches user data in memory to avoid repeated slow database calls.
📋 What You'll Learn
Create a function to simulate fetching user data from a slow database
Create a cache object to store user data
Add logic to check the cache before fetching from the database
Return cached data if available, otherwise fetch and cache it
💡 Why This Matters
🌍 Real World
Caching is used in web servers to speed up responses by storing data temporarily, reducing slow database calls.
💼 Career
Understanding caching is important for backend developers to build efficient and scalable applications.
Progress0 / 4 steps
1
Create a function to simulate slow database fetch
Create a function called fetchUserFromDB that takes a userId parameter and returns a Promise that resolves to an object { id: userId, name: 'User' + userId } after 100 milliseconds.
Node.js
Need a hint?

Use setTimeout inside a Promise to simulate delay.

2
Create a cache object
Create an empty object called cache to store cached user data.
Node.js
Need a hint?

Use a plain object to store cached data by userId keys.

3
Add caching logic to fetch user data
Create an async function called getUser that takes userId. Inside, check if cache[userId] exists. If yes, return it. Otherwise, call fetchUserFromDB(userId), store the result in cache[userId], then return it.
Node.js
Need a hint?

Use async/await and check the cache before fetching.

4
Export the getUser function
Add module.exports = { getUser }; at the end to export the getUser function for use in other files.
Node.js
Need a hint?

Use module.exports to export the function.