ioredis.js tutorial


ioredis.js is a new, performance focused Redis client for Node.js. It is used by the online commerce company, Alibaba. It also supports ES6 types such as Map and Set and also implements support for Promises, which the other big Redis client, <a href=“”>node_redis</a>, is not. <a href=“”>ioredis.js</a> is newly released so in the next sections of this blog post I will show you some basic usage of this client.

Installing the client

npm install ioredis

Instantiating the client

var Redis = require("ioredis");
//basic constructor - Connect to
var redis = new Redis();

There are multiple ways to instantiate the Redis client. Above I presented the basic method of doing it and bellow I will show you more methods:

var Redis = new Redis(6400);
var Redis = new Redis(6379, '');
var Redis = new Redis(6379, '');
//, db 4
new Redis('redis://:authpassword@');   
new Redis('/tmp/redis.sock');   
new Redis({
  port: 6379,          // Redis port
  host: '',   // Redis host
  family: 4,           // 4(IPv4) or 6(IPv6)
  password: 'auth'
  db: 0

I also suggest, as best practice in general to use environment variables for connectivity credentials/urls/ports.

Basic functionality

The two basic Redis operations set and get can be done pretty straight forward with ioredis.js.


redis.set('key', 'value');

Get using callbacks:

redis.get('key', function (err, result) {
  console.log(result); //will display 'value'

Get using promises:

redis.get('key').then(function (result) {
  console.log(result); //will display 'value'

Adding a set of values:

// Arguments to commands are flatten, so the following are same
redis.sadd('set', 1, 3, 5, 7);
// or 
redis.sadd('set', [1, 3, 5, 7]);

Getting a set of values using callback:

redis.smembers('set', function(err, result) {
  console.log(result); //will display '1, 3, 5, 7'

Getting a set of values using promises:

redis.smembers('set').then(function(result) {
  console.log(result); //will display '1, 3, 5, 7'

All Redis commands are supported by ioredis.js, both using callbacks or promises. Just use each command as a method name for the Redis client.

Handling binary data

ioredis.js also handles binary data by adding and retrieving buffers.


redis.set('key', new Buffer('value'));

Every command has a method that returns a buffer. By doing that you have to append “Buffer” to the command name.


redis.getBuffer('key', function (err, result) {
  // result is a buffer.

ioredis.js also supports pipelining, transactions, offline queues, Sentinel and Cluster. For these advanced operations you can find a pretty detailed description here.

I hope this tutorial is informative enough to give you a start with ioredis.js.