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

  • Future Trends in AI Chatbots: What to Expect in the Next Decade

    Artificial Intelligence (AI) chatbots have become indispensable across industries. The absolute conversational capabilities of AI chatbots are enhancing customer engagement, streamlining operations, and transforming how businesses interact with users. As technology evolves, the future of AI chatbots holds revolutionary advancements that will redefine their capabilities. So, let’s start with exploring the AI chatbot trends: Future […]

  • Linguistics and NLP: Enhancing AI Chatbots for Multilingual Support

    In today’s interconnected world, businesses and individuals often communicate across linguistic boundaries. The growing need for seamless communication has driven significant advancements in artificial intelligence (AI), particularly in natural language processing (NLP) and linguistics. AI chatbots with multilingual support, are revolutionizing global customer engagement and service delivery. This blog explores how linguistics and NLP are […]

  • How Reinforcement Learning is Shaping the Next Generation of AI Chatbots?

    AI chatbots are no longer just about answering “What are your working hours?” or guiding users through FAQs. They’re becoming conversation partners, problem solvers and even reporting managers and sales agents. What’s driving this transformation? Enter Reinforcement Learning (RL)—a type of machine learning that’s changing the way chatbots think, learn, and respond. At Codalien Technologies, […]

  • AI Chatbots for Sales Team Automation: The Critical Role of AI Sales Assistants in Automating Your Sales Team

    Sales teams are the heart of any successful business, but managing them effectively can often feel like trying to juggle flaming swords. The constant pressure to generate leads, maintain relationships, and close deals leaves your team overwhelmed, spending more time on administrative tasks than actual selling. Here’s where AI-powered sales assistants step in to completely […]

  • Transforming HR with AI Assistants: The Comprehensive Guide

    The role of Human Resources (HR) is critical for the smooth functioning of any organization, from handling administrative tasks to shaping workplace culture and driving strategic decisions. However, traditional methods often fall short of meeting the demands of a modern, dynamic workforce. This is where our Human Resource AI assistants enter —a game-changing tool that […]

  • How Conversational AI Chatbots Improve Conversion Rates in E-Commerce?

    The digital shopping experience has evolved, with Conversational AI Chatbots revolutionizing customer interactions in e-commerce. These AI-powered systems offer personalized, real-time communication with customers, streamlining the buying process and increasing conversion rates. But how do Conversational AI Chatbots improve e-commerce conversion rates, and what are the real benefits for customers? In this blog, we’ll break […]

Click to Copy