Node.js and Redis Tutorial

August 4, 2019
by Rahil Shaikh
  • nodejs redis

In this Node.js tutorial, we will learn about Redis and how to use it with Node.js.

What is Redis?

Redis is an in-memory data store, meaning it stores data within the RAM for quick access. It’s typically used for caching frequently queried data, for eg: something like user-session information. Other than this it can also be used as a message broker or as temporary storage.

Storing data in-memory means the data is lost in case of server reboot unless we enable persistence in Redis. This is enabled by default.  Redis supports a number of data-structures like strings, hashes, sets, lists, etc.

All these benefits combined with easy use makes Redis one of the popular in-memory datastore. Redis also works really well with Node.js and there are a number of client’s written for node.js and Redis.

Installing Redis – Linux

sudo apt-get update

sudo apt-get install redis-server

sudo systemctl enable redis-server.service

To start the server run…

redis-server

To run as a service in background

sudo systemctl start redis-server.service

 

To check if Redis is properly installed and running…

redis-cli

When your type ping  is should return PONG.

127.0.0.1:6379> ping
PONG
127.0.0.1:6379>

 

Using Redis with Node.js

To use Redis with node.js we need a Node.js client. We can install it by running…

npm i redis --save

By default, Redis runs on PORT-6379, unless specified something else. Now create a new file app.js and open it in your text editor.

const redis = require('redis');
const client = redis.createClient(6379, 'localhost');

client.on('connect', ()=>{
console.log('redis connected');
});

On running the app it should say, ‘redis connected’. If it doesn’t then check if Redis server is running. To catch any errors, add the listener to error event.

client.on('error', ()=>{
console.log('redis errored');
});

If the Redis installation is password protected, we can pass the password as options while connecting.

const client = redis.createClient(6379, 'localhost', {password: "boo"});

Now that we have seen how to connect to Redis, let’s try and store some data into it.

Redis uses SET command to store data and GET command to retrive data.

Let’s see it in action.

Storing Strings

To store a string as key-value pair…

client.set('food', 'Pasta', function(err, reply) {
console.log(reply);
});

To retrieve a key-value…

client.get('food', function(err, reply) {
console.log(reply);
});

Storing Lists

client.rpush(['food', 'pasta', 'Noodles'], function(err, reply) {
    console.log(reply); //prints 2
});

The above command creates a list called food and pushes 2 values into it. As you can see we are using rpush command which will push new elements from the right, similarly we can use lpush to push elements from the left.

To retrieve all the elements from the list we can use the lrange command.

client.lrange('food', 0, -1, function(err, reply) {
    console.log(reply); // ['pasta', 'Noodles']
});

Note we pass -1 as the 3rd argument to retrieve all the elements, or we can pass a specific index to only get values up to that index.

Storing hashes/objects

To store an object we can use the hmset method.

client.hmset('food', {
    'breakfast': 'Tea',
    'Lunch': 'Pasta',
    'Dinner': 'Noodles'
});

We can retrieve this by using…

client.hgetall('food', function(err, object) {
    console.log(object);
});

Alternatively, in Node.js we can also store the entire object, as a string using the set function.

const food = {
    'breakfast': 'Tea',
    'Lunch': 'Pasta',
    'Dinner': 'Noodles'
}
client.set('food', JSON.stringify(food));

Then we will need to parse the string when we retrieve it.

client.get('food', function(err, reply) {
console.log(JSON.parse(reply));
});

Expiring keys

One other really useful feature of Redis is its ability to have temporary keys. This is particularly useful for storing session information.

client.set('key1', 'val1');
client.expire('key1', 30);

The above code snippet will set key1 with an expiry time of 30 sec.

Common Interview Questions

Now that we know how to use Redis with node.js let’s see a few questions related to Redis you might be asked in an interview.

What is Redis and what is its use case?

This is the most important question and usually, the first question apart from (Have you worked with Redis?) you will be asked. We have already answered this at the start of this article.

How can Redis be used as a Message Broker?

Redis provides pub/sub mechanism which allows publishers to publish messages into a channel and subscribers to subscribe to one or more message channels.
Publishers and Subscribers work independently of one another, where a publisher will not know about the subscribers subscribing to a channel and vice-versa. This decoupling of pubs and subs allows Redis to achieve greater scalability.

Do we lose Redis data on shutdown? If yes how can we avoid it?

Redis works fast by storing data in-memory, and typically server shutdown means loss of in-memory data. However, Redis can be configured to persist data to disk and restore.

What are some of the Data Types supported by Redis?

  • String
  • Hashes (Objects)
  • Lists (Similar to arrays)
  • Sets
  • Sorted Sets
  • Bitmaps
  • HyperLogs

Conclusion

In this Node.js Redis Tutorial, we saw how we can install Redis and use it with Node.js. We also learned it’s use cases and had a look at some of the related interview questions.
I hope this article benefited you in one way or another and you take away some learning points from the same. Feel free to share it if you love it.

Learning Never Stops…

About

Engineer. Blogger. Thinker. Loves programming and working with emerging tech. We can also talk on Football, Gaming, World Politics, Monetary Systems.

Get notified on our new articles

Subscribe to get the latest on Node.js, Angular, Blockchain and more. We never spam!
First Name:
Email:

Leave a Comment