Open In App

How to access cache data in Node.js ?

Improve
Improve
Like Article
Like
Save
Share
Report

Cache: Caching is a technique used for improving the performance of servers and a lot of devices used in day-to-day life.
In caching, the result of certain computation or task is stored somewhere, and if the same computation is required again, it is served from that location itself rather than doing the computation again. This reduces computation and improves performance, thereby providing a better user experience.
A lot of apps cache data for the first time they’re fired, hence are able to efficiently provide responses. Similarly, the majority of servers have advanced cached mechanisms for endpoints that serve the same response for the majority of the time.

Cache can be stored using various techniques like in-memory cache, file cache or a separate cache database.
This article demonstrates usage of caching in Node.js using package node-cache which is an in-memory caching module.

Implementing cache demo using node-cache.

Create basic node js server. Building simple nodejs REST API using express

Ensure that node is installed, by following command:

node -v

Navigate to desired project directory and Install express (for creating server) and node-cache npm packages using the following command:

npm i express node-cache

Project structure:

Example: Create a file server.js in the directory with following code:

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 !')
})


Run the following command:

node server.js

Output: Open the link: http://localhost:8000/ in desired browser to verify

Home Page

Create a simple API that performs a costly operation to serve response (To simulate an external API / Database query).

Add following code at the end of server.js

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.

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.

Implement caching with following approach:

  • 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.

Final code in server.js:

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)
     }
})


  • 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.  



Last Updated : 15 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads