0
0
Expressframework~30 mins

In-memory caching with node-cache in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
In-memory caching with node-cache in Express
📖 Scenario: You are building a simple Express server that fetches user data. To make it faster, you want to store some data temporarily in memory so the server does not fetch it again and again.
🎯 Goal: Create an Express server that uses node-cache to store user data in memory. The server should return cached data if available, or fetch and cache it if not.
📋 What You'll Learn
Create an Express app with a GET route at /user/:id
Use node-cache to store user data in memory
Set a cache time-to-live (TTL) of 10 seconds
Return cached data if it exists, otherwise simulate fetching data and cache it
💡 Why This Matters
🌍 Real World
In-memory caching helps speed up web servers by storing frequently requested data temporarily, reducing database or API calls.
💼 Career
Understanding caching is important for backend developers to improve app performance and scalability.
Progress0 / 4 steps
1
Setup Express app and import node-cache
Write code to import express and NodeCache from node-cache. Then create an Express app by calling express() and assign it to a variable called app.
Express
Need a hint?

Use import statements to bring in the modules. Then call express() to create the app.

2
Create a cache instance with 10 seconds TTL
Create a new NodeCache instance called cache with a time-to-live (TTL) option set to 10 seconds.
Express
Need a hint?

Use new NodeCache({ stdTTL: 10 }) to create the cache with 10 seconds TTL.

3
Add GET route to use cache for user data
Add a GET route handler on /user/:id using app.get. Inside the handler, get the id from req.params. Check if the user data exists in cache using cache.get(id). If it exists, return it as JSON. If not, simulate fetching user data by creating an object { id, name: `User ${id}` }, store it in cache with cache.set(id, userData), and return it as JSON.
Express
Need a hint?

Use app.get with /user/:id. Use req.params.id to get the id. Use cache.get(id) to check cache. If no cache, create user data and store with cache.set(id, userData).

4
Start the Express server on port 3000
Add code to start the Express server by calling app.listen on port 3000. Provide a callback function that logs the message 'Server running on port 3000'.
Express
Need a hint?

Use app.listen(3000, () => { console.log('Server running on port 3000') }) to start the server.