How to Access Cache Data in Node.js ?
Last Updated :
20 Jun, 2024
Caching is an essential technique in software development that helps improve application performance and scalability by temporarily storing frequently accessed data. In Node.js, caching can significantly reduce database load, minimize API response times, and optimize resource utilization. This article will guide you through various methods to access and manage cache data in a Node.js application.
Introduction to Caching
Caching involves storing copies of data in a temporary storage location, or cache, to quickly access it upon subsequent requests. This approach minimizes the need to repeatedly retrieve data from a slower backend data store, such as a database or an external API.
Why Use Caching?
- Improved Performance: Cache reduces latency and accelerates data retrieval.
- Reduced Database Load: Caching reduces the frequency of database queries, leading to better resource utilization.
- Enhanced Scalability: Efficient caching helps applications handle increased loads without degrading performance.
- Cost Efficiency: Reducing the need for repeated data retrieval from costly resources like databases or external services can save operational costs.
Caching Strategies
- In-Memory Caching: Stores data in the application’s memory for fast access.
- Distributed Caching: Uses external cache services like Redis to store data, allowing multiple instances of an application to access the same cache.
- Persistent Caching: Stores cache data in a persistent storage system that survives application restarts.
- Building simple nodejs REST API using express.
Steps to Set Up Project
Step 1: Make a folder structure for the project.
mkdir myapp
Step 2:Â Navigate to project directory
cd myapp
Step 3: Initialize the NodeJs project inside the myapp folder.
npm init -y
Step 4: Install the necessary packages/libraries in your project using the following commands.
npm i express node-cache

Project structure:

The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.19.2",
"node-cache": "^5.1.2"
}
Example: Create a file server.js in the directory with following code:
Node
// server.js
// Importing express module
const express = require('express')
// Creating an express object
const app = express()
// Starting server using listen function on port 8000
app.listen(8000, err => {
if(err)
console.log("Error while starting server")
else
console.log("Server has been started at port 8000")
})
app.get('/', (req, res)=>{
res.send('Home page !')
})
Step to Run Application:Â Run the application using the following command from the root directory of the project
node server.js
Output:Â Your project will be shown in the URL http://localhost:3000/

Home PageExample: Add following code at the end of server.js, Create a simple API that performs a costly operation to serve response
(To simulate an external API / Database query).
Node
// server.js
function heavyComputation(){
let temp = 0;
for(let i=0; i<100000; i++)
temp = (Math.random()*5342)%i;
return 123;
}
app.get('/api', (req, res)=>{
let result = heavyComputation();
res.send("Result: "+result);
})
Stop server by Ctrl+C and start again by node server.js. In the browser, open Network tab in Chrome Dev Tools and check time required to get response.

Approach for Implementing caching
- On API request, check if the cache has key already set using has(key) function
- If the cache has the key, retrieve the cached value by get(key) function and use it instead of performing operation again. (This saves time)
- If the cache doesn't have a key, perform the operations required, and before sending the response, set the value for that key so that further requests can be responded to directly through cached data.
Implement node-cache
Import Node-cache npm module and create a new NodeCache object
const NodeCache = require( "node-cache" );
const myCache = new NodeCache();
Node-cache has following major functions
- .set(key, val, [ ttl ]): Used to set some value corresponding to a particular key in the cache. This same key must be used to retrieve this value.
- .get(key):Used to get value set to specified key. It returns undefined, if the key is not already present.
- has(key): Used to check if the cache already has some value set for specified key. Returns true if present otherwise false.
Example: Final Code for accessing chache data using above module.
Node
// server.js
// Importing express module
const express = require('express')
// Importing NodeCache and creating a
// new object called myCache
const NodeCache = require('node-cache')
const myCache = new NodeCache()
// Creating an express object
const app = express()
// Starting server using listen
// function on port 8000
app.listen(8000, err => {
if(err)
console.log("Error while starting server")
else
console.log(
"Server has been started at port 8000")
})
app.get('/', (req, res)=>{
res.send('Home page !')
})
// Function to demonstrate heavy computation
// like API requests, database queries, etc.
function heavyComputation(){
let temp = 0;
for(let i=0; i<100000; i++)
temp = (Math.random()*5342)%i;
return 123;
}
app.get('/api', (req, res)=>{
// If cache has key, retrieve value
// from cache itself
if(myCache.has('uniqueKey')){
console.log('Retrieved value from cache !!')
// Serve response from cache using
// myCache.get(key)
res.send("Result: " + myCache.get('uniqueKey'))
}else{
// Perform operation, since cache
// doesn't have key
let result = heavyComputation()
// Set value for same key, in order to
// serve future requests efficiently
myCache.set('uniqueKey', result)
console.log('Value not present in cache,'
+ ' performing computation')
res.send("Result: " + result)
}
})
Explanation:
- Stop server by Ctrl+C and start again by node server.js.
- Reload the webpage once. This time computation is performed. It can be seen on console also
- Reload the webpage again. This time data is served from cache as seen on console.
- Further reloads will serve data from cache, thereby saving computations.

Note: The difference between response time is not significant here, since the computation is very less, however for large and scaled projects, it provides a massive performance boost.Â
For example, GeeksforGeeks also uses advanced caching mechanisms for various purposes to achieve efficiency. Â
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Decorators in Python In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
Sliding Window Technique Sliding Window Technique is a method used to solve problems that involve subarray or substring or window. The main idea is to use the results of previous window to do computations for the next window. This technique is commonly used in algorithms like finding subarrays with a specific sum, finding t
13 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. Example of an AVL Tree:The balance factors for different nodes are : 12 :1, 8:1, 18:1, 5:1, 11:0, 17:0 and 4:0. Since all differences
4 min read
What is a Neural Network? Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns, and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamenta
14 min read