What is ioredis?
ioredis is a robust, performance-focused, and full-featured Redis client for Node.js. It supports both Redis commands and the cluster mode introduced in Redis 3.0. It provides a more intuitive and flexible way to interact with a Redis server or a cluster of Redis servers, offering features like automatic reconnection, offline queueing, and support for transactions, pub/sub, and Lua scripting.
What are ioredis's main functionalities?
Basic Commands
Execute basic Redis commands such as SET and GET. This example demonstrates setting and getting the value of a key.
const Redis = require('ioredis');
const redis = new Redis();
redis.set('foo', 'bar');
redis.get('foo', (err, result) => {
console.log(result);
});
Publish/Subscribe
Use Redis' pub/sub capabilities to publish messages to a channel and subscribe to receive messages from that channel.
const Redis = require('ioredis');
const subscriber = new Redis();
const publisher = new Redis();
subscriber.subscribe('news', () => {
publisher.publish('news', 'Hello world!');
});
subscriber.on('message', (channel, message) => {
console.log(`Received \
${message} from ${channel}`);
});
Transactions
Perform transactions using the MULTI/EXEC commands to execute multiple commands atomically.
const Redis = require('ioredis');
const redis = new Redis();
redis.multi()
.set('foo', 'bar')
.get('foo')
.exec((err, results) => {
console.log(results);
});
Pipeline
Use pipelining to send multiple commands to the server without waiting for the replies, improving performance.
const Redis = require('ioredis');
const redis = new Redis();
redis.pipeline()
.set('foo', 'bar')
.get('foo')
.del('foo')
.exec((err, results) => {
console.log(results);
});
Lua Scripting
Extend Redis with Lua scripting. This example defines a custom command that gets the current value of a key and sets it to a new value atomically.
const Redis = require('ioredis');
const redis = new Redis();
redis.defineCommand('getAndSet', {
numberOfKeys: 1,
lua: 'return {redis.call('get', KEYS[1]), redis.call('set', KEYS[1], ARGV[1])}'
});
redis.getAndSet('foo', 'new value', (err, result) => {
console.log(result);
});
Other packages similar to ioredis
redis-commands
redis-commands is not a full client but a comprehensive list of all Redis commands for use in JavaScript. It's useful for developers who want to ensure compatibility or extend their own Redis client implementations. Unlike ioredis, it doesn't provide a client interface or connection management.
ioredis
[WIP] A delightful, performance-focused Redis client for Node and io.js
Instal
$ npm install ioredis
Usage
var Redis = require('ioredis');
var redis = new Redis();
redis.set('foo', 'bar');
redis.get('foo', function (err, result) {
console.log(result);
});
redis.get('foo').then(function (result) {
console.log(result);
});