How to use redis with node.js

In this tutorial you’ll learn how to work with Redis in Node.js. Redis is an open source advanced key-value cache and store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, sorted sets, bitmaps and hyperloglogs.

In Node.js you can use several modules to interface with Redis server, but for this tutorial, we will use the one recommended by Redis. In our opinion, the Node.js Redis module looks like it is a mature, fast and stable choice for interfacing with the Redis database natively.

The Node.js Redis module is hosted on npm and we can install it via npm. To install it in your project, simply run the following command in your project root directory:

> npm install redis

The preceding command should install the Redis module in your project.

Note that npm is a package manager which provides a central repository for custom open sourced modules for Node.js and JavaScript. npm makes it simple to manage modules, their versions and distribution. As shown earlier, we used the npm install command to install the required module in our project.

Making the connection to the Redis database

The first thing you need to do in order to work with any database is to establish a connection with it. To do this, we will use the redisClient provided in the redis module to create the connection. Let’s go step by step on the connection building process. First create an empty file in your project directory and write the code as described below:

Load the redis module and create a client

We need to load the redis module in our program, for that we will use require function as described here:

//Let’s load the redis module.
var redis = require("redis");

Now we need to create a client which is connected to our redis-server:

//Let’s create a client for redis server we need to connect to.
var client = redis.createClient(6379, '127.0.0.1', {/*options*/});

We used the createClient method provided in the redis module to create our client. The parameters are as follows createClient(port, host/IP, [options]).

If redis is running on the same computer localhost, then we can avoid passing in any parameters to the createClient method. But it is strongly recommended that you specify the port and IP explicitly, such that there are no unknown assumptions and code is easy to understand and maintain. You can also pass options optionally if required. See the list of available options here on the module documentation. But for basic usage you should be good with default options preconfigured within the module.

Bind some events

The client object created above is an EventEmitter and it emits certain events and we need to listen to the error event in case there is a connection error as well as the ready event to know when we are ready to communicate with the server. It also fires a connect event, but we recommend you to use ready event unless you specified in configuration to defer ready events.

//Handle error event
client.on('error', function (err) {
  console.log(err);
});

//Listen for when redis is ready to receive commands.
client.on('ready', function () {
  console.log('Hurray! We are ready!');

  //Do stuff here...

});

[Optional] Provide Auth Password

In case your server needs a password to connect to it, then you need to specify that. This step is totally optional and not mandatory unless your server requires an auth password to connect. If we also erroneously provide the auth passwords for redis servers that do not need passwords, then the program will run normally with a warning message indicating that the password was supplied but was not required.

client.auth('password', function (err, authResp) {
  console.log('Error:', err, 'Resp:', authResp);
});
So now if summarize all of the preceding steps, our file should look like:
//Let’s load the redis module.
var redis = require("redis");

//Let’s create a client for Redis. This client will communicate to server.
var client = redis.createClient(6379, '127.0.0.1', {/*options*/});

//Handle error event
client.on('error', function (err) {
  console.log(err);
});

//Listen for when Redis is ready to receive commands.
client.on('ready', function () {
  console.log('Hurray! We are ready!');

  //Do stuff here...

});

client.auth('password', function (err, authResp) {
  console.log('Error:', err, 'Resp:', authResp);
});

Firing commands to Redis server

Now that we have the connection ready, we can send commands to the Redis server. To run the commands keep the following in mind:

  • The Redis commands ex: get, set, mget etc. are available with exact same name on the client object we created above. For example, if you need to fire the Redis set command, then all you have to do is run client.set() method with the desired arguments. There is an exact mapping between Redis commands and function names on the client object.
  • The arguments to the methods on the client object; for example, client.set() will be same as those that you pass to the Redis command natively. For example: In Redis if you fire set ‘key’ ‘val’ it will be equivalent to client.set(‘key’, ‘value’). The last argument in all these methods is callback. callback is optional and is triggered after that command is executed in Redis. The *arguments in callback function are callback(err, reply). Incase there is an error in running that command it will be sent in error argument, and the reply of the command will be sent in reply argument. The callback is optional but if you want to have a look on the output of the command then you can use the Helper callback function provided by the Redis module named redis.print. Example: client.set(‘key’, ‘value’, redis.print).

Let’s try to fire some commands to our Redis database:

//Listen for when Redis is ready to receive commands.
client.on('ready', function () {
  console.log('Hurray! We are ready!');

  //Last argument is callback which is optional
  client.set('Name', 'Redis Demo');

  //Using redis.print to print results.
  client.set('Date', new Date(), redis.print);

  //Using mget to get all the keys specified at once
  client.mget(['Name', 'Date'], function (err, reply) {
    if (err) {
      return console.log(err);
    }
    //Reply will be an array in case of multiple returns from the Redis command.
    console.log('Program Type: %s , Last Updated: %s', reply[0], reply[1]);
  });
});

Similarly you can fire any Redis command using the client object available.

Changing parsers for boosting performance

The Node.js redis module supports custom parsers. The default module parser is written in javascript and there is a module named hiredis, which is Node.js binding to the official hiredis parser. In layman terms, parser is the interface between the Redis protocol and our system. If you install the hiredis module using npm, the redis module will automatically use hiredis as a parser by default. To install hiredis do the following:

> npm install hiredis

Now the redis module will use hiredis as a parser and you will experience a performance boost. We have some benchmarks provided by the redis module owners, which are as follows:

Without hiredis (Javascript parser)

Benchmarks are as follows:

PING:  20000 ops 42283.30 ops/sec
SET:   20000 ops 32948.93 ops/sec
GET:   20000 ops 28694.40 ops/sec
INCR:  20000 ops 39370.08 ops/sec
LPUSH: 20000 ops 36429.87 ops/sec
LRANGE (10 elements):  20000 ops 9891.20 ops/sec
LRANGE (100 elements): 20000 ops 1384.56 ops/sec

With hiredis (C parser)

Benchmarks are as follows:

PING:  20000 ops 46189.38 ops/sec
SET:   20000 ops 41237.11 ops/sec
GET:   20000 ops 39682.54 ops/sec
INCR:  20000 ops 40080.16 ops/sec
LPUSH: 20000 ops 41152.26 ops/sec
LRANGE (10 elements):  20000 ops 36563.07 ops/sec
LRANGE (100 elements): 20000 ops 21834.06 ops/sec

These benchmarks clearly state that the hiredis parser is better, especially in the case of lrange command. Note:: One thing to be aware of when using the hiredis parser is to remember that you have to recompile it whenever you update your version of Node to avoid malfunctions.

Conclusion

In this tutorial, you learned how to interface with the redis server in Node.js. We took a look at the officially recommended module node-redis and explored how we can use it. We also learned how to increase the performance of the communication between application and Redis server by using the native hiredis module.


Posted

in

by

Recent Post

  • Generative AI for IT: Integration approaches, use cases, challenges, ROI evaluation and future outlook

    Generative AI is a game-changer in the IT sector, driving significant cost reductions and operational efficiencies. According to a BCG analysis, Generative AI (GenAI) has the potential to deliver up to 10% savings on IT spending—a transformation that is reshaping multiple facets of technology. The impact is especially profound in application development, where nearly 75% […]

  • Generative AI in Manufacturing: Integration approaches, use cases and future outlook

    Generative AI is reshaping manufacturing by providing advanced solutions to longstanding challenges in the industry. With its ability to streamline production, optimize resource allocation, and enhance quality control, GenAI offers manufacturers new levels of operational efficiency and innovation. Unlike traditional automation, which primarily focuses on repetitive tasks, GenAI enables more dynamic and data-driven decision-making processes, […]

  • Generative AI in Healthcare: Integration, use cases, challenges, ROI, and future outlook

    Generative AI (GenAI) is revolutionizing the healthcare industry, enabling enhanced patient care, operational efficiency, and advanced decision-making. From automating administrative workflows to assisting in clinical diagnoses, GenAI is reshaping how healthcare providers, payers, and technology firms deliver services. A Q1 2024 survey of 100 US healthcare leaders revealed that over 70% have already implemented or […]

  • Generative AI in Hospitality: Integration, Use Cases, Challenges, and Future Outlook

    Generative AI is revolutionizing the hospitality industry, redefining guest experiences, and streamlining operations with intelligent automation. According to market research, the generative AI market in the hospitality sector was valued at USD 16.3 billion in 2023 and is projected to skyrocket to USD 439 billion by 2033, reflecting an impressive CAGR of 40.2% from 2024 […]

  • Generative AI for Contract Management: Overview, Use Cases, Implementation Strategies, and Future Trends

    Effective contract management is a cornerstone of business success, ensuring compliance, operational efficiency, and seamless negotiations. Yet, managing complex agreements across departments often proves daunting, particularly for large organizations. The TalkTo Application, a generative AI-powered platform, redefines contract management by automating and optimizing critical processes, enabling businesses to reduce operational friction and improve financial outcomes. […]

  • Generative AI in customer service: Integration approaches, use cases, best practices, and future outlook

    Introduction The rise of generative AI is revolutionizing customer service, heralding a new era of intelligent, responsive, and personalized customer interactions. As businesses strive to meet evolving customer expectations, these advanced technologies are becoming indispensable for creating dynamic and meaningful engagement. But what does this shift mean for the future of customer relationships? Generative AI […]

Click to Copy