Hi Guest

MobileUser

1 HomePage 1 Jobs 1 WalkIn 1Articles  

Cat Exam

 :) Latest Topic
AJAX
VB.NET
SQL Query
UDDI
CLASS
JavaScript Questions
SharePoint Interview
SilverLight
WCF
general knowledge
 ASP.NET
 :) Hot Jobs
 
 :) Latest Articles


  

 


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

Home >> 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



 
 Input Your Comments Or suggestions(If Any)
 Name
 Email(optional)
 Comments


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?






 
Top Searches:asp net questions vb net questions sql query uddl questions class javascript Questions sharepoint interview questions and concept silverlight questions and concept wcf questions beans general knowledge ajax questions
PHP | Biztalk | Testing | SAP | HR |