I am Hack Sparrow
Captain of the Internets.

Using Redis with Node.js

How to use Redis with Node.js

Redis is an in-memory 'database' system which gives an incredibly fast read-write access to data. Once you start using Node.js, you are very likely to be introduced to NoSQL, and Redis might strike you as one of the most outstanding among them.

Do you want to use Redis with Node.js, but have no idea where to begin? This concise but illustrative article will show you just how to get Redis kick started with Node.js.

Node.js has an excellently written Redis client it's named redis. You can download it from here, or you can install it using npm.

$ npm install redis

Once you have installed the redis client library you can start using it in your Node.js code as shown below. Make sure you have the following code in all the files where you intend to connect to Redis from Node.js.

var _redis = require("redis"),
var redis = _redis.createClient();

Here on, it is up to you to learn the various Redis commands and execute them using the redis client. Look at some examples below, using the client is very straightforward.

A very simple example. We get the value of the key named "name".

redis.get('name', function(error, result) {
    if (error) console.log('Error: '+ error);
    else console.log('Name: ' + result);

Here we set the key name to the form value name submitted via a POST request.

redis.set('name', req.body.name, function(error, result) {
    if (error) res.send('Error: ' + error);
    else res.send('Saved');

In the next example, we set multiple values to a hash table. Notice how the key and the hash values are collected from the POST data.

var key = 'movies.' + req.body.movie_id;
redis.hmset(key, 'title', req.body.title, 'year', req.body.year, function(error, result) {
    if (error) res.send('Error: ' + error);
    else res.send('Movie details saved!');

So that's it about using Redis with Node.js. Not really that much of a big deal, the bigger challenge will be learning all the Redis commands and planning how to name your data keys.

2 Responses to “Using Redis with Node.js”

  1. Luc Juggery says:


    Also, db.multi can be very handy if you need to make several requests at the same time. It will then act as a transactional mode:

    [“set”, “status”, “good”],
    [“hmset”, “user”, {name: “Jonh”, age: 30}],
    ]).exec(function (err, replies) {

    } else {



  2. Chetan says:

    Hi I get this error:

    Error: Redis connection to failed – connect ECONNREFUSED

    How to resolve this?

Make a Comment