How to use Redis with Node.js (ioredis)


This article goes over how to use Redis with Node.js via npm package ioredis.

Install

Install ioredis:

npm install ioredis

Connect

Import Redis:

const Redis = require('ioredis');

Connect to Redis with options:

const redis = new Redis({
  host: process.env.REDIS_HOSTNAME,
  port: process.env.REDIS_PORT,
  password: process.env.REDIS_PASSWORD,
});

For example, to connect to local Redis:

const redis = new Redis({
  host: 'localhost',
  port: 6379,
});

Alternatively, Redis can be connected with a URL string:

const redis = new Redis(process.env.REDIS_URL);

The URL string has the format:

redis://<REDIS_USER>:<REDIS_PASSWORD>@<REDIS_HOST>:<REDIS_PORT>

So the local Redis URL is:

redis://localhost:6379

Commands

set

Set key with value:

await redis.set('key', 'value'); // returns 'OK'

get

Get value from key:

await redis.get('key'); // returns 'value'

del

Delete key-value pair:

await redis.del('key'); // returns 1

Delete multiple key-value pairs:

await redis.del(['key1', 'key2']);

del doesn’t allow pattern matching (*).

keys

Search by key:

await redis.keys('key'); // returns ['key']

Search by keys:

await redis.keys('key1', 'key2');
await redis.keys(['key1', 'key2']);

Search by pattern:

await redis.keys('k*'); // returns ['key']

Get all keys:

await redis.keys('*'); // returns ['key']

scan

Scan performs better than keys if there’s a lot of data:

await redis.scan(0, 'MATCH', '*'); // returns ['0', ['key']]

scanStream creates a ReadableStream:

const stream = redis.scanStream({ match: '*' });
let keys = [];

stream.on('data', (resultKeys) => {
  keys = keys.concat(resultKeys);
});

stream.on('end', () => {
  console.log(keys); // returns ['key']
});

stream.on('error', (error) => {
  throw error;
});

Demo

Replit:



Please support this site and join our Discord!