crackyourinterview.com


To improves our performance please Like Share Subscribe(Will boost us)

Caching in Node.js with syntax and example?
Question Posted on 01 May 2024Home >> WEB >> Node.js >> Caching in Node.js with syntax and example?

Caching in Node.js with syntax and example?
To understand this we will take an example which will demonstrates how to implement caching in Node.js application.

Here in this example we will take a simple web application which fetches user information from a remote API. And every time a user visit the application which makes and API call to get the user data. So fetching the same user data everytime every request can be inefficient.

To optimize this process,we will introduce caching by using Node.js. ANd to do that we will use node-cache package for in-memory caching in this example.

Start code for Cache in Node.Js
To start caching in Node.js in first step we will start by installing node-cache package using npm:-


npm install node.cache



Now we will jump to the Node.js application and create a file name cacheapp.js and which require the below necessary modules:-


const express = require('express');
const NodeCache = require('node-cache');
const app = express();
const cache = new NodeCache();



Now we implement the caching middleware. Here we will create a middleware function which will intercepts request, here we will checks if the data is available in cache, and this will serves if we found that. It retrieves the data from the API and caches it and sens that data in response.


app.get('/users/:id', (req, res) => {
const userId = req.params.id;

// Check if the data exists in the cache
const cachedData = cache.get(userId);

if (cachedData) {
// Serve the data from cache
res.json({ data: cachedData });
} else {
// Fetch the data from the API
fetchDataFromAPI(userId)
.then((userData) => {
// Cache the data for future use
cache.set(userId, userData);

// Send the response
res.json({ data: userData });
})
.catch((error) => {
res.status(500).json({ error: 'Internal Server Error' });
});
}
});

function fetchDataFromAPI(userId) {
// Simulate API call to retrieve user data
return new Promise((resolve, reject) => {
// Assume the API call takes some time
setTimeout(() => {
// Mock user data
const userData = {
id: userId,
name: 'Paul Adam',
email: 'TestEmail@example.com'
};
resolve(userData);
}, 200);
});
}



And to test application we will start Node.js command prompt and start the Node.js server and then make a request to run below Node.js command. And get the below answer:-


node cacheapp.js






GET http://localhost:3000/users/123



If we run the application first time it will fetch data from API and then cache it and this will send the response. And other subsequent request for same use will served directly from the cache and this will improve the response times and also reduce the load of the API.

And by implementing caching we can optimize the performance of Node.js application by minimize expensive API calls and serv data from cache when possible.
0
0



.


Most Visited Questions:-

Deep Learning Questions Answers
Below are the different Deep Leaning Questions and answer a More...

Continuous Integration Questions Answers
Below are the 20 odd questions for CI or Continuous Integra More...

Derived relationships in Association Rule Mining are represented in the form of __________.
Derived relationships in Association Rule Mining are repres More...

What is Gulpjs and some multiple choice questions on Gulp
Gulpjs is an open source whihc helps in building Javascript More...

Microservices Architecture Questions Answers
Below are the different questions on Microservices Architec More...




Other Important Questions

REPL stands for ____________________.

Which of the following is true about EventEmitter.on property?

Which method of fs module is used to truncate a file?

What is Node.js?

Which method of fs module is used to close a file?






@2014-2022 Crackyourinterview (All rights reserved)
Privacy Policy - Disclaimer - Sitemap