Open In App

How to Access Cache Data in Node.js ?

Last Updated : 20 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Page

Example: 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.  




Next Article

Similar Reads