How to use Redis with Node.js (ioredis)

remarkablemark
Mar 23, 2022

--

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

Redis and Node.js
Redis and Node.js

Install

Install ioredis:

npm install ioredis

Connect

Import Redis:

Connect to Redis with options:

For example, to connect to local Redis:

Alternatively, Redis can be connected with a URL string:

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:

get

Get value from key:

del

Delete key-value pair:

Delete multiple key-value pairs:

del doesn’t allow pattern matching (*).

keys

Search by key:

Search by keys:

Search by pattern:

Get all keys:

scan

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

scanStream creates a ReadableStream:

Demo

Replit:

--

--