0
# ioredis
1
2
ioredis is a robust, performance-focused, and full-featured Redis client for Node.js written in TypeScript. It provides complete Redis command support, clustering capabilities, sentinel management, and advanced features like pipelining, pub/sub, and Lua scripting with strong type safety.
3
4
## Package Information
5
6
- **Package Name**: ioredis
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install ioredis`
10
11
## Core Imports
12
13
```typescript
14
import Redis from "ioredis";
15
import { Cluster } from "ioredis";
16
```
17
18
For CommonJS:
19
20
```javascript
21
const Redis = require("ioredis");
22
const { Cluster } = Redis;
23
```
24
25
## Basic Usage
26
27
```typescript
28
import Redis from "ioredis";
29
30
// Connect to Redis
31
const redis = new Redis(); // defaults to localhost:6379
32
33
// Basic operations
34
await redis.set("key", "value");
35
const value = await redis.get("key");
36
37
// Using with configuration
38
const redis2 = new Redis({
39
host: "redis.example.com",
40
port: 6380,
41
password: "secret",
42
db: 1,
43
});
44
45
// Redis Cluster
46
import { Cluster } from "ioredis";
47
48
const cluster = new Cluster([
49
{ host: "127.0.0.1", port: 7000 },
50
{ host: "127.0.0.1", port: 7001 },
51
]);
52
53
await cluster.set("key", "value");
54
```
55
56
## Architecture
57
58
ioredis is built around several key components:
59
60
- **Redis Client**: Main client class supporting standalone Redis and Sentinel configurations
61
- **Cluster Client**: Specialized client for Redis Cluster deployments with automatic slot management
62
- **Command System**: Comprehensive Redis command interface with TypeScript typing
63
- **Connection Management**: Robust connection handling with reconnection, retries, and pooling
64
- **Pipeline System**: Command batching for performance optimization
65
- **Pub/Sub System**: Full publish/subscribe support including pattern subscriptions
66
- **Event System**: EventEmitter-based architecture for connection lifecycle management
67
68
## Capabilities
69
70
### Redis Client
71
72
Core Redis client for connecting to standalone Redis servers or Sentinel-managed deployments. Supports all Redis commands with full TypeScript typing.
73
74
```typescript { .api }
75
class Redis extends EventEmitter {
76
constructor();
77
constructor(port: number);
78
constructor(path: string);
79
constructor(options: RedisOptions);
80
constructor(port: number, options: RedisOptions);
81
constructor(port: number, host: string);
82
constructor(port: number, host: string, options: RedisOptions);
83
constructor(path: string, options: RedisOptions);
84
85
connect(callback?: Callback<void>): Promise<void>;
86
quit(callback?: Callback<"OK">): Promise<"OK">;
87
duplicate(override?: Partial<RedisOptions>): Redis;
88
}
89
```
90
91
[Redis Client](./redis-client.md)
92
93
### Cluster Client
94
95
Redis Cluster client with automatic slot management, node discovery, and failover handling.
96
97
```typescript { .api }
98
class Cluster extends EventEmitter {
99
constructor(startupNodes: ClusterNode[], options?: ClusterOptions);
100
101
connect(): Promise<void>;
102
quit(callback?: Callback<"OK">): Promise<"OK">;
103
nodes(role?: NodeRole): Redis[];
104
refreshSlotsCache(callback?: Callback<void>): void;
105
}
106
107
type ClusterNode = string | number | {
108
host?: string;
109
port?: number;
110
};
111
```
112
113
[Cluster Operations](./cluster.md)
114
115
### Configuration Options
116
117
Comprehensive configuration interfaces for Redis connections including network settings, behavior options, and advanced features.
118
119
```typescript { .api }
120
interface RedisOptions {
121
host?: string;
122
port?: number;
123
password?: string;
124
db?: number;
125
retryStrategy?: (times: number) => number | void | null;
126
enableAutoPipelining?: boolean;
127
maxRetriesPerRequest?: number | null;
128
// ... extensive additional options
129
}
130
131
interface ClusterOptions extends Partial<RedisOptions> {
132
clusterRetryStrategy?: (times: number, reason?: Error) => number | void | null;
133
scaleReads?: NodeRole | Function;
134
maxRedirections?: number;
135
// ... additional cluster-specific options
136
}
137
```
138
139
[Configuration](./configuration.md)
140
141
### Command Execution
142
143
Complete Redis command interface with promise-based returns, callback support, and proper TypeScript typing for all Redis operations.
144
145
```typescript { .api }
146
// String operations
147
get(key: RedisKey): Promise<string | null>;
148
set(key: RedisKey, value: RedisValue): Promise<"OK">;
149
set(key: RedisKey, value: RedisValue, expiryMode: "EX", time: number): Promise<"OK">;
150
151
// Hash operations
152
hget(key: RedisKey, field: string): Promise<string | null>;
153
hset(key: RedisKey, field: string, value: RedisValue): Promise<number>;
154
155
// List operations
156
lpush(key: RedisKey, ...values: RedisValue[]): Promise<number>;
157
lrange(key: RedisKey, start: number, stop: number): Promise<string[]>;
158
```
159
160
[Redis Commands](./commands.md)
161
162
### Pipelining & Transactions
163
164
Efficient command batching and atomic transaction support with MULTI/EXEC operations.
165
166
```typescript { .api }
167
pipeline(commands?: unknown[][]): ChainableCommander;
168
multi(options?: { pipeline?: boolean }): ChainableCommander | Promise<"OK">;
169
170
interface ChainableCommander {
171
exec(callback?: Callback): Promise<Array<[Error | null, any]>>;
172
// All Redis commands available for chaining
173
}
174
```
175
176
[Pipelining & Transactions](./pipelining.md)
177
178
### Pub/Sub Messaging
179
180
Complete publish/subscribe support including pattern subscriptions and message handling.
181
182
```typescript { .api }
183
subscribe(...channels: string[]): Promise<number>;
184
unsubscribe(...channels: string[]): Promise<number>;
185
psubscribe(...patterns: string[]): Promise<number>;
186
publish(channel: string, message: string): Promise<number>;
187
188
// Event handlers
189
on(event: 'message', listener: (channel: string, message: string) => void): this;
190
on(event: 'pmessage', listener: (pattern: string, channel: string, message: string) => void): this;
191
```
192
193
[Pub/Sub Messaging](./pubsub.md)
194
195
### Streaming Operations
196
197
Readable streams for efficient scanning of large datasets using Redis SCAN operations.
198
199
```typescript { .api }
200
scanStream(options?: ScanStreamOptions): ScanStream;
201
sscanStream(key: string, options?: ScanStreamOptions): ScanStream;
202
hscanStream(key: string, options?: ScanStreamOptions): ScanStream;
203
zscanStream(key: string, options?: ScanStreamOptions): ScanStream;
204
205
interface ScanStreamOptions {
206
match?: string;
207
count?: number;
208
type?: string;
209
}
210
211
class ScanStream extends Readable {
212
close(): void;
213
}
214
```
215
216
[Streaming](./streaming.md)
217
218
### Lua Scripting
219
220
Define custom Redis commands using Lua scripts with automatic script caching and EVAL/EVALSHA optimization.
221
222
```typescript { .api }
223
defineCommand(
224
name: string,
225
definition: {
226
lua: string;
227
numberOfKeys?: number;
228
readOnly?: boolean;
229
}
230
): void;
231
232
// Built-in scripting commands
233
eval(script: string, numKeys: number, ...keysAndArgs: any[]): Promise<any>;
234
evalsha(sha: string, numKeys: number, ...keysAndArgs: any[]): Promise<any>;
235
script(subcommand: "LOAD" | "EXISTS" | "FLUSH" | "KILL", ...args: any[]): Promise<any>;
236
```
237
238
**Usage Examples:**
239
240
```typescript
241
import Redis from "ioredis";
242
243
const redis = new Redis();
244
245
// Define a custom command
246
redis.defineCommand("myecho", {
247
numberOfKeys: 1,
248
lua: "return KEYS[1] .. ARGV[1]",
249
});
250
251
// Use the custom command (TypeScript will provide typing)
252
const result = await redis.myecho("key", "value"); // Returns "keyvalue"
253
254
// Define command via constructor options (see Configuration docs)
255
const redis2 = new Redis({
256
scripts: {
257
increment: {
258
lua: `
259
local key = KEYS[1]
260
local limit = tonumber(ARGV[1])
261
local current = redis.call('GET', key) or 0
262
if tonumber(current) < limit then
263
return redis.call('INCR', key)
264
else
265
return current
266
end
267
`,
268
numberOfKeys: 1,
269
}
270
}
271
});
272
```
273
274
[Configuration](./configuration.md)
275
276
## Core Types
277
278
```typescript { .api }
279
type RedisKey = string | Buffer;
280
type RedisValue = string | Buffer | number;
281
type NodeRole = "master" | "slave" | "all";
282
type Callback<T> = (err?: Error | null, result?: T) => void;
283
284
interface SentinelAddress {
285
host: string;
286
port: number;
287
}
288
289
interface ClusterNode {
290
host?: string;
291
port?: number;
292
}
293
294
type NatMapFunction = (key: string) => { host: string; port: number } | null;
295
type NatMap = {
296
[key: string]: { host: string; port: number };
297
} | NatMapFunction;
298
299
type DNSLookupFunction = (
300
hostname: string,
301
callback: (err: NodeJS.ErrnoException | null | undefined, address: string, family?: number) => void
302
) => void;
303
304
type DNSResolveSrvFunction = (
305
hostname: string,
306
callback: (err: NodeJS.ErrnoException | null | undefined, records?: any[]) => void
307
) => void;
308
309
// Utility function for debugging Redis responses
310
function print(err: Error | null, reply?: any): void;
311
312
// ReplyError is imported from redis-errors package
313
const ReplyError: typeof import("redis-errors").ReplyError;
314
```