Nowadays, you can see the use of JavaScript programming language in various programs and its impact on digital life. One of the concerns of JavaScript programmers has always been to be able to run their code on the server side, except for the user’s browser. That is, with the help of JavaScript, they can create the appearance and logic of their web service together. One of the environments that allows programmers to run their JavaScript code on the server side is Node.JS. In this article, we intend to teach you How to Optimize Node.JS Apps with Redis Caching. If you want to buy VPS, you can visit the plans offered on the Eldernode website.
Table of Contents
Tutorial speed up Node.JS Apps with Redis Caching
Applications of Node.JS
Node.JS is an open source platform for developing server-side and network applications. This platform is written based on JavaScript language and Node.JS hosting can implement on Windows, Linux and MAC operating systems.
Among the applications of Node.JS, the following can be mentioned:
1- Creating Single Page Applications (SPA)
SPA refers to programs that all parts are implementing in one page. SPA is mostly using to build social networks, email services, video sharing sites, etc. One of the most famous sites built in this way is the YouTube video sharing service. Since Node.JS supports asynchronous programming well, it is considering a good choice for making SPA programs.
2- Creating RTA programs
RTA stands for real-time app. For example, Google Sheets, Spreadsheets or Slack are such programs. In general, interactive applications, project management tools, video and audio conferencing, and other RTA applications perform heavy I/O operations.
3- Creating a chat room
One of the most famous examples of RTA applications are chat rooms and messengers. You probably use different messengers and chat rooms every day and you would like to create a chat room for yourself. In fact Node.JS is a great choice for this. If you intend to make such a product, you should pay attention to various things such as tolerating a lot of user traffic, the lightness of the product, the high speed of sending messages, etc. All these things can implement on the server side with the help of Node.JS and a JavaScript framework like Express.js.
4- Creating online games under web browser
The idea of creating a chat room is attractive, but it becomes more attractive when you write a game for the web browser and provide a chat room along with that game. With the help of Node.JS, you can develop web games. In fact, by combining HTML5 technologies and JavaScript tools (such as Express.js or Socket.io, etc.), you can create attractive 2D games such as Ancient Beast or PaintWar.
Introduction to Redis
Redis is an in-RAM data structure repository, which supports many data types such as strings, hashes, sets, sorted sets, etc. Basically, Redis is a key-value store.
Any type of value inside Redis is stored against a binary-secure key. This value can be anything from an empty string to a long hash string. Every application should support a predefined map for naming Redis keys, to avoid any naming confusion. Storing data as key-value pairs means no schema. In this system, key is of string type and value is of any type that you like; Number, string, JSON and so on.
How to Install Redis Server/Client
After you are familiar with Node.JS and Redis, in this section we are going to show you How to Install Redis Server/Client. To do this, just follow the steps below. In the first step, you need to install Redis by running the following command:
npm i redis
Optimizing Node.JS Apps with Redis Caching
After installing Redis, you can now create a Redis client instance in your Node.js application using the following commands. It is important to note that you specify the host and port on which the server is running. By doing this, the client will be able to connect to the server easily.
const redis = require("redis"); const client = redis.createClient({ host: "127.0.0.1", port: 6379, });
You can create middleware to manage the cache in Node.JS. The following function will check whether the requested data is cached. Using the following function, a key will be created based on the URL to retrieve and store the data:
function cache(req, res, next) { const key = "__express__" + req.originalUrl || req.url; client.get(key).then(reply => { if (reply) { res.send(JSON.parse(reply)); } else { res.sendResponse = res.send; res.send = (body) => { //expire in 1 min client.set(key, JSON.stringify(body), {'EX':60}); res.sendResponse(body); }; next(); } }).catch(err=>{ console.log(err); res.status(500).send(err) }); }
You can use the cache middleware in the program by running the following commands:
app.use(cache);
As you can see in the following commands, the cache middleware is used to create a large amount of data:
app.get("/data", (req, res) => { let data = 0; for (let i = 1; i < 100000000; i++) { data += 1; } res.json(data); });
Finally, you can connect the redis client to the server by running the following command:
app.listen(3000, () => { console.log("Server listening on port 3000"); client.connect().then(()=> { console.log('redis is connected') }) });
Conclusion
As mentioned, Node.JS is a platform built on Google Chrome’s JavaScript engine that makes it easy to create and scale web applications. In this article, we tried to teach you How to Optimize Node.JS Apps with Redis Caching. If you have any question, you can share it with us in the comments section.