0
# Redis Commands
1
2
Complete implementation of all Redis commands with type-safe parameters and return values. The client provides over 700 Redis commands organized by data type and functionality, with both uppercase method names and lowercase aliases.
3
4
## Capabilities
5
6
### String Commands
7
8
Basic string operations for storing and retrieving string values.
9
10
```typescript { .api }
11
/**
12
* Get the value of a key
13
* @param key - The key to get
14
* @returns The value of the key, or null if key does not exist
15
*/
16
get(key: RedisArgument): Promise<BlobStringReply | null>;
17
GET(key: RedisArgument): Promise<BlobStringReply | null>;
18
19
/**
20
* Set the string value of a key
21
* @param key - The key to set
22
* @param value - The value to set
23
* @param options - Optional set options (expiration, conditions)
24
* @returns 'OK' if successful, null if condition not met
25
*/
26
set(key: RedisArgument, value: RedisArgument, options?: SetOptions): Promise<SimpleStringReply<'OK'> | null>;
27
SET(key: RedisArgument, value: RedisArgument, options?: SetOptions): Promise<SimpleStringReply<'OK'> | null>;
28
29
/**
30
* Increment the integer value of a key by one
31
* @param key - The key to increment
32
* @returns The new value after increment
33
*/
34
incr(key: RedisArgument): Promise<NumberReply>;
35
INCR(key: RedisArgument): Promise<NumberReply>;
36
37
/**
38
* Increment the integer value of a key by amount
39
* @param key - The key to increment
40
* @param increment - The amount to increment by
41
* @returns The new value after increment
42
*/
43
incrBy(key: RedisArgument, increment: number): Promise<NumberReply>;
44
INCRBY(key: RedisArgument, increment: number): Promise<NumberReply>;
45
46
/**
47
* Append a value to a key
48
* @param key - The key to append to
49
* @param value - The value to append
50
* @returns The length of the string after append
51
*/
52
append(key: RedisArgument, value: RedisArgument): Promise<NumberReply>;
53
APPEND(key: RedisArgument, value: RedisArgument): Promise<NumberReply>;
54
55
/**
56
* Get the length of the string value stored at key
57
* @param key - The key to measure
58
* @returns The length of the string, or 0 if key does not exist
59
*/
60
strlen(key: RedisArgument): Promise<NumberReply>;
61
STRLEN(key: RedisArgument): Promise<NumberReply>;
62
63
interface SetOptions {
64
/** Set expiration in seconds */
65
EX?: number;
66
/** Set expiration in milliseconds */
67
PX?: number;
68
/** Set expiration at Unix timestamp in seconds */
69
EXAT?: number;
70
/** Set expiration at Unix timestamp in milliseconds */
71
PXAT?: number;
72
/** Only set if key does not exist */
73
NX?: boolean;
74
/** Only set if key exists */
75
XX?: boolean;
76
/** Keep existing TTL */
77
KEEPTTL?: boolean;
78
/** Return previous value */
79
GET?: boolean;
80
}
81
```
82
83
**Usage Examples:**
84
85
```typescript
86
import { createClient } from "redis";
87
88
const client = createClient();
89
await client.connect();
90
91
// Basic string operations
92
await client.set("name", "John");
93
const name = await client.get("name"); // "John"
94
95
// Set with expiration
96
await client.set("session", "abc123", { EX: 3600 }); // Expires in 1 hour
97
98
// Conditional set
99
const result = await client.set("counter", "1", { NX: true }); // Only if not exists
100
101
// Increment operations
102
await client.set("visits", "10");
103
await client.incr("visits"); // 11
104
await client.incrBy("visits", 5); // 16
105
106
// String manipulation
107
await client.append("message", " world"); // Append to existing value
108
const length = await client.strlen("message"); // Get string length
109
```
110
111
### Hash Commands
112
113
Hash field operations for storing and manipulating hash tables.
114
115
```typescript { .api }
116
/**
117
* Set the string value of a hash field
118
* @param key - The hash key
119
* @param field - The field name
120
* @param value - The value to set
121
* @returns 1 if new field, 0 if field was updated
122
*/
123
hSet(key: RedisArgument, field: RedisArgument, value: RedisArgument): Promise<NumberReply>;
124
HSET(key: RedisArgument, field: RedisArgument, value: RedisArgument): Promise<NumberReply>;
125
126
/**
127
* Get the value of a hash field
128
* @param key - The hash key
129
* @param field - The field name
130
* @returns The value of the field, or null if field does not exist
131
*/
132
hGet(key: RedisArgument, field: RedisArgument): Promise<BlobStringReply | null>;
133
HGET(key: RedisArgument, field: RedisArgument): Promise<BlobStringReply | null>;
134
135
/**
136
* Get all fields and values in a hash
137
* @param key - The hash key
138
* @returns Object with all hash fields and values
139
*/
140
hGetAll(key: RedisArgument): Promise<Record<string, BlobStringReply>>;
141
HGETALL(key: RedisArgument): Promise<Record<string, BlobStringReply>>;
142
143
/**
144
* Set multiple hash fields to multiple values
145
* @param key - The hash key
146
* @param hash - Object with field-value pairs
147
* @returns 'OK'
148
*/
149
hMSet(key: RedisArgument, hash: Record<string | number, RedisArgument>): Promise<SimpleStringReply<'OK'>>;
150
HMSET(key: RedisArgument, hash: Record<string | number, RedisArgument>): Promise<SimpleStringReply<'OK'>>;
151
152
/**
153
* Get the values of multiple hash fields
154
* @param key - The hash key
155
* @param fields - Array of field names
156
* @returns Array of field values (null for non-existent fields)
157
*/
158
hMGet(key: RedisArgument, fields: RedisArgument[]): Promise<ArrayReply<BlobStringReply | null>>;
159
HMGET(key: RedisArgument, fields: RedisArgument[]): Promise<ArrayReply<BlobStringReply | null>>;
160
161
/**
162
* Delete one or more hash fields
163
* @param key - The hash key
164
* @param fields - Field names to delete
165
* @returns Number of fields that were removed
166
*/
167
hDel(key: RedisArgument, ...fields: RedisArgument[]): Promise<NumberReply>;
168
HDEL(key: RedisArgument, ...fields: RedisArgument[]): Promise<NumberReply>;
169
170
/**
171
* Determine if a hash field exists
172
* @param key - The hash key
173
* @param field - The field name
174
* @returns 1 if field exists, 0 otherwise
175
*/
176
hExists(key: RedisArgument, field: RedisArgument): Promise<BooleanReply>;
177
HEXISTS(key: RedisArgument, field: RedisArgument): Promise<BooleanReply>;
178
179
/**
180
* Get the number of fields in a hash
181
* @param key - The hash key
182
* @returns Number of fields in the hash
183
*/
184
hLen(key: RedisArgument): Promise<NumberReply>;
185
HLEN(key: RedisArgument): Promise<NumberReply>;
186
```
187
188
**Usage Examples:**
189
190
```typescript
191
// Hash operations
192
await client.hSet("user:1", "name", "Alice");
193
await client.hSet("user:1", "email", "alice@example.com");
194
195
// Set multiple fields at once
196
await client.hMSet("user:2", {
197
name: "Bob",
198
email: "bob@example.com",
199
age: "30"
200
});
201
202
// Get single field
203
const name = await client.hGet("user:1", "name"); // "Alice"
204
205
// Get multiple fields
206
const fields = await client.hMGet("user:1", ["name", "email"]);
207
208
// Get all fields and values
209
const user = await client.hGetAll("user:1");
210
// { name: "Alice", email: "alice@example.com" }
211
212
// Check field existence
213
const exists = await client.hExists("user:1", "age"); // 0 (false)
214
215
// Get hash size
216
const size = await client.hLen("user:1"); // 2
217
```
218
219
### List Commands
220
221
List operations for working with ordered collections.
222
223
```typescript { .api }
224
/**
225
* Insert all specified values at the head of the list
226
* @param key - The list key
227
* @param elements - Elements to push
228
* @returns The length of the list after push
229
*/
230
lPush(key: RedisArgument, ...elements: RedisArgument[]): Promise<NumberReply>;
231
LPUSH(key: RedisArgument, ...elements: RedisArgument[]): Promise<NumberReply>;
232
233
/**
234
* Insert all specified values at the tail of the list
235
* @param key - The list key
236
* @param elements - Elements to push
237
* @returns The length of the list after push
238
*/
239
rPush(key: RedisArgument, ...elements: RedisArgument[]): Promise<NumberReply>;
240
RPUSH(key: RedisArgument, ...elements: RedisArgument[]): Promise<NumberReply>;
241
242
/**
243
* Remove and return the first element of the list
244
* @param key - The list key
245
* @returns The first element, or null if list is empty
246
*/
247
lPop(key: RedisArgument): Promise<BlobStringReply | null>;
248
LPOP(key: RedisArgument): Promise<BlobStringReply | null>;
249
250
/**
251
* Remove and return the last element of the list
252
* @param key - The list key
253
* @returns The last element, or null if list is empty
254
*/
255
rPop(key: RedisArgument): Promise<BlobStringReply | null>;
256
RPOP(key: RedisArgument): Promise<BlobStringReply | null>;
257
258
/**
259
* Get a range of elements from a list
260
* @param key - The list key
261
* @param start - Start index (0-based, can be negative)
262
* @param stop - Stop index (inclusive, can be negative)
263
* @returns Array of elements in the specified range
264
*/
265
lRange(key: RedisArgument, start: number, stop: number): Promise<ArrayReply<BlobStringReply>>;
266
LRANGE(key: RedisArgument, start: number, stop: number): Promise<ArrayReply<BlobStringReply>>;
267
268
/**
269
* Get the length of a list
270
* @param key - The list key
271
* @returns The length of the list
272
*/
273
lLen(key: RedisArgument): Promise<NumberReply>;
274
LLEN(key: RedisArgument): Promise<NumberReply>;
275
276
/**
277
* Blocking pop from multiple lists (left side)
278
* @param keys - List keys to pop from
279
* @param timeout - Timeout in seconds (0 = block indefinitely)
280
* @returns Array with key and popped element, or null if timeout
281
*/
282
blPop(keys: RedisArgument[], timeout: number): Promise<ArrayReply<BlobStringReply> | null>;
283
BLPOP(keys: RedisArgument[], timeout: number): Promise<ArrayReply<BlobStringReply> | null>;
284
```
285
286
**Usage Examples:**
287
288
```typescript
289
// List operations
290
await client.lPush("tasks", "task1", "task2", "task3");
291
await client.rPush("tasks", "task4"); // Add to end
292
293
// Get list contents
294
const tasks = await client.lRange("tasks", 0, -1); // All elements
295
// ["task3", "task2", "task1", "task4"] (newest first)
296
297
// Pop elements
298
const first = await client.lPop("tasks"); // "task3"
299
const last = await client.rPop("tasks"); // "task4"
300
301
// List length
302
const length = await client.lLen("tasks"); // 2
303
304
// Blocking pop with timeout
305
const result = await client.blPop(["queue1", "queue2"], 5); // Wait 5 seconds
306
if (result) {
307
const [key, value] = result;
308
console.log(`Popped "${value}" from "${key}"`);
309
}
310
```
311
312
### Set Commands
313
314
Set operations for working with unordered collections of unique elements.
315
316
```typescript { .api }
317
/**
318
* Add one or more members to a set
319
* @param key - The set key
320
* @param members - Members to add
321
* @returns Number of elements added to the set
322
*/
323
sAdd(key: RedisArgument, ...members: RedisArgument[]): Promise<NumberReply>;
324
SADD(key: RedisArgument, ...members: RedisArgument[]): Promise<NumberReply>;
325
326
/**
327
* Get all members in a set
328
* @param key - The set key
329
* @returns Array of all members in the set
330
*/
331
sMembers(key: RedisArgument): Promise<ArrayReply<BlobStringReply>>;
332
SMEMBERS(key: RedisArgument): Promise<ArrayReply<BlobStringReply>>;
333
334
/**
335
* Determine if a member is in a set
336
* @param key - The set key
337
* @param member - The member to check
338
* @returns 1 if member exists, 0 otherwise
339
*/
340
sIsMember(key: RedisArgument, member: RedisArgument): Promise<BooleanReply>;
341
SISMEMBER(key: RedisArgument, member: RedisArgument): Promise<BooleanReply>;
342
343
/**
344
* Remove one or more members from a set
345
* @param key - The set key
346
* @param members - Members to remove
347
* @returns Number of members removed from the set
348
*/
349
sRem(key: RedisArgument, ...members: RedisArgument[]): Promise<NumberReply>;
350
SREM(key: RedisArgument, ...members: RedisArgument[]): Promise<NumberReply>;
351
352
/**
353
* Get the number of members in a set
354
* @param key - The set key
355
* @returns The cardinality of the set
356
*/
357
sCard(key: RedisArgument): Promise<NumberReply>;
358
SCARD(key: RedisArgument): Promise<NumberReply>;
359
360
/**
361
* Intersect multiple sets
362
* @param keys - Set keys to intersect
363
* @returns Array of members in the intersection
364
*/
365
sInter(keys: RedisArgument[]): Promise<ArrayReply<BlobStringReply>>;
366
SINTER(keys: RedisArgument[]): Promise<ArrayReply<BlobStringReply>>;
367
368
/**
369
* Union multiple sets
370
* @param keys - Set keys to union
371
* @returns Array of members in the union
372
*/
373
sUnion(keys: RedisArgument[]): Promise<ArrayReply<BlobStringReply>>;
374
SUNION(keys: RedisArgument[]): Promise<ArrayReply<BlobStringReply>>;
375
```
376
377
**Usage Examples:**
378
379
```typescript
380
// Set operations
381
await client.sAdd("fruits", "apple", "banana", "orange");
382
await client.sAdd("citrus", "orange", "lemon", "lime");
383
384
// Check membership
385
const hasApple = await client.sIsMember("fruits", "apple"); // 1 (true)
386
387
// Get all members
388
const fruits = await client.sMembers("fruits"); // ["apple", "banana", "orange"]
389
390
// Set operations
391
const intersection = await client.sInter(["fruits", "citrus"]); // ["orange"]
392
const union = await client.sUnion(["fruits", "citrus"]);
393
// ["apple", "banana", "orange", "lemon", "lime"]
394
395
// Set size
396
const count = await client.sCard("fruits"); // 3
397
398
// Remove members
399
await client.sRem("fruits", "banana");
400
```
401
402
### Sorted Set Commands
403
404
Sorted set operations for working with ordered collections with scores.
405
406
```typescript { .api }
407
/**
408
* Add one or more members to a sorted set
409
* @param key - The sorted set key
410
* @param members - Array of score-member pairs
411
* @returns Number of elements added to the sorted set
412
*/
413
zAdd(key: RedisArgument, ...members: Array<{ score: number; value: RedisArgument }>): Promise<NumberReply>;
414
ZADD(key: RedisArgument, ...members: Array<{ score: number; value: RedisArgument }>): Promise<NumberReply>;
415
416
/**
417
* Get a range of members in a sorted set by index
418
* @param key - The sorted set key
419
* @param start - Start index
420
* @param stop - Stop index
421
* @param options - Optional parameters (WITHSCORES, REV)
422
* @returns Array of members (and scores if WITHSCORES)
423
*/
424
zRange(key: RedisArgument, start: number, stop: number, options?: ZRangeOptions): Promise<ArrayReply<BlobStringReply>>;
425
ZRANGE(key: RedisArgument, start: number, stop: number, options?: ZRangeOptions): Promise<ArrayReply<BlobStringReply>>;
426
427
/**
428
* Get the rank of a member in a sorted set
429
* @param key - The sorted set key
430
* @param member - The member
431
* @returns The rank (0-based index), or null if member doesn't exist
432
*/
433
zRank(key: RedisArgument, member: RedisArgument): Promise<NumberReply | null>;
434
ZRANK(key: RedisArgument, member: RedisArgument): Promise<NumberReply | null>;
435
436
/**
437
* Get the score of a member in a sorted set
438
* @param key - The sorted set key
439
* @param member - The member
440
* @returns The score, or null if member doesn't exist
441
*/
442
zScore(key: RedisArgument, member: RedisArgument): Promise<BlobStringReply | null>;
443
ZSCORE(key: RedisArgument, member: RedisArgument): Promise<BlobStringReply | null>;
444
445
/**
446
* Get the number of members in a sorted set
447
* @param key - The sorted set key
448
* @returns The cardinality of the sorted set
449
*/
450
zCard(key: RedisArgument): Promise<NumberReply>;
451
ZCARD(key: RedisArgument): Promise<NumberReply>;
452
453
interface ZRangeOptions {
454
/** Return scores along with members */
455
WITHSCORES?: boolean;
456
/** Reverse the ordering */
457
REV?: boolean;
458
/** Limit results (offset and count) */
459
LIMIT?: { offset: number; count: number };
460
}
461
```
462
463
**Usage Examples:**
464
465
```typescript
466
// Sorted set operations
467
await client.zAdd("leaderboard",
468
{ score: 100, value: "alice" },
469
{ score: 85, value: "bob" },
470
{ score: 92, value: "charlie" }
471
);
472
473
// Get top players (highest scores)
474
const top3 = await client.zRange("leaderboard", 0, 2, { REV: true });
475
// ["alice", "charlie", "bob"]
476
477
// Get with scores
478
const withScores = await client.zRange("leaderboard", 0, -1, { WITHSCORES: true });
479
// ["bob", "85", "charlie", "92", "alice", "100"]
480
481
// Get player rank (0-based, lowest score = rank 0)
482
const rank = await client.zRank("leaderboard", "alice"); // 2 (highest score)
483
484
// Get player score
485
const score = await client.zScore("leaderboard", "alice"); // "100"
486
487
// Get total players
488
const total = await client.zCard("leaderboard"); // 3
489
```
490
491
### Stream Commands
492
493
Stream operations for working with Redis Streams.
494
495
```typescript { .api }
496
/**
497
* Append an entry to a stream
498
* @param key - The stream key
499
* @param id - Entry ID ('*' for auto-generation)
500
* @param fields - Field-value pairs for the entry
501
* @returns The ID of the added entry
502
*/
503
xAdd(key: RedisArgument, id: string, fields: Record<string, RedisArgument>): Promise<BlobStringReply>;
504
XADD(key: RedisArgument, id: string, fields: Record<string, RedisArgument>): Promise<BlobStringReply>;
505
506
/**
507
* Read data from streams
508
* @param streams - Stream specifications with start IDs
509
* @param options - Optional parameters (COUNT, BLOCK)
510
* @returns Stream data grouped by stream key
511
*/
512
xRead(streams: Record<string, string>, options?: XReadOptions): Promise<ArrayReply<StreamEntry> | null>;
513
XREAD(streams: Record<string, string>, options?: XReadOptions): Promise<ArrayReply<StreamEntry> | null>;
514
515
/**
516
* Get stream length
517
* @param key - The stream key
518
* @returns Number of entries in the stream
519
*/
520
xLen(key: RedisArgument): Promise<NumberReply>;
521
XLEN(key: RedisArgument): Promise<NumberReply>;
522
523
interface XReadOptions {
524
/** Maximum number of entries to return per stream */
525
COUNT?: number;
526
/** Block for specified milliseconds if no entries available */
527
BLOCK?: number;
528
}
529
530
interface StreamEntry {
531
name: string;
532
messages: Array<{
533
id: string;
534
message: Record<string, BlobStringReply>;
535
}>;
536
}
537
```
538
539
**Usage Examples:**
540
541
```typescript
542
// Stream operations
543
const entryId = await client.xAdd("events", "*", {
544
type: "login",
545
user: "alice",
546
timestamp: Date.now().toString()
547
});
548
549
// Read from stream
550
const entries = await client.xRead({ "events": "0-0" }, { COUNT: 10 });
551
if (entries) {
552
for (const stream of entries) {
553
console.log(`Stream: ${stream.name}`);
554
for (const message of stream.messages) {
555
console.log(`ID: ${message.id}`, message.message);
556
}
557
}
558
}
559
560
// Stream length
561
const length = await client.xLen("events");
562
```
563
564
### Key Management Commands
565
566
General key operations that work across all data types.
567
568
```typescript { .api }
569
/**
570
* Determine if a key exists
571
* @param keys - Keys to check
572
* @returns Number of existing keys
573
*/
574
exists(...keys: RedisArgument[]): Promise<NumberReply>;
575
EXISTS(...keys: RedisArgument[]): Promise<NumberReply>;
576
577
/**
578
* Delete one or more keys
579
* @param keys - Keys to delete
580
* @returns Number of keys deleted
581
*/
582
del(...keys: RedisArgument[]): Promise<NumberReply>;
583
DEL(...keys: RedisArgument[]): Promise<NumberReply>;
584
585
/**
586
* Set a key's time to live in seconds
587
* @param key - The key
588
* @param seconds - TTL in seconds
589
* @returns 1 if timeout was set, 0 if key doesn't exist
590
*/
591
expire(key: RedisArgument, seconds: number): Promise<BooleanReply>;
592
EXPIRE(key: RedisArgument, seconds: number): Promise<BooleanReply>;
593
594
/**
595
* Get the time to live for a key in seconds
596
* @param key - The key
597
* @returns TTL in seconds, -1 if no TTL, -2 if key doesn't exist
598
*/
599
ttl(key: RedisArgument): Promise<NumberReply>;
600
TTL(key: RedisArgument): Promise<NumberReply>;
601
602
/**
603
* Get the type of a key
604
* @param key - The key
605
* @returns The type of the key
606
*/
607
type(key: RedisArgument): Promise<BlobStringReply>;
608
TYPE(key: RedisArgument): Promise<BlobStringReply>;
609
610
/**
611
* Find all keys matching a pattern
612
* @param pattern - Glob-style pattern
613
* @returns Array of matching keys
614
*/
615
keys(pattern: string): Promise<ArrayReply<BlobStringReply>>;
616
KEYS(pattern: string): Promise<ArrayReply<BlobStringReply>>;
617
```
618
619
**Usage Examples:**
620
621
```typescript
622
// Key management
623
await client.set("temp:123", "value");
624
625
// Check existence
626
const exists = await client.exists("temp:123"); // 1
627
628
// Set expiration
629
await client.expire("temp:123", 3600); // Expire in 1 hour
630
631
// Check TTL
632
const ttl = await client.ttl("temp:123"); // ~3600
633
634
// Get key type
635
const type = await client.type("temp:123"); // "string"
636
637
// Find keys by pattern
638
const tempKeys = await client.keys("temp:*"); // ["temp:123"]
639
640
// Delete keys
641
const deleted = await client.del("temp:123"); // 1
642
```
643
644
### Transaction Commands
645
646
Transaction support with MULTI/EXEC and optimistic locking with WATCH.
647
648
```typescript { .api }
649
/**
650
* Watch keys for changes during transaction
651
* @param keys - Keys to watch
652
* @returns 'OK'
653
*/
654
watch(...keys: RedisArgument[]): Promise<SimpleStringReply<'OK'>>;
655
WATCH(...keys: RedisArgument[]): Promise<SimpleStringReply<'OK'>>;
656
657
/**
658
* Unwatch all previously watched keys
659
* @returns 'OK'
660
*/
661
unwatch(): Promise<SimpleStringReply<'OK'>>;
662
UNWATCH(): Promise<SimpleStringReply<'OK'>>;
663
664
/**
665
* Start a transaction
666
* @returns Multi command interface
667
*/
668
multi(): RedisClientMultiCommandType;
669
MULTI(): RedisClientMultiCommandType;
670
671
interface RedisClientMultiCommandType {
672
/** Execute all queued commands */
673
exec(): Promise<ArrayReply<any> | null>;
674
/** Discard all queued commands */
675
discard(): Promise<SimpleStringReply<'OK'>>;
676
/** Queue commands for execution */
677
[key: string]: (...args: any[]) => RedisClientMultiCommandType;
678
}
679
```
680
681
**Usage Examples:**
682
683
```typescript
684
// Transaction with optimistic locking
685
await client.watch("balance:alice", "balance:bob");
686
687
const aliceBalance = parseInt(await client.get("balance:alice") || "0");
688
const bobBalance = parseInt(await client.get("balance:bob") || "0");
689
690
if (aliceBalance >= 100) {
691
const result = await client
692
.multi()
693
.decrBy("balance:alice", 100)
694
.incrBy("balance:bob", 100)
695
.exec();
696
697
if (result === null) {
698
console.log("Transaction aborted - balances were modified");
699
} else {
700
console.log("Transfer completed", result);
701
}
702
} else {
703
await client.unwatch();
704
console.log("Insufficient balance");
705
}
706
```
707
708
## Iterator Support
709
710
```typescript { .api }
711
/**
712
* Scan keys matching pattern
713
* @param options - Scan options (MATCH, COUNT, TYPE)
714
* @returns AsyncIterator of matching keys
715
*/
716
scanIterator(options?: ScanOptions): AsyncIterableIterator<BlobStringReply>;
717
718
/**
719
* Scan hash fields
720
* @param key - Hash key
721
* @param options - Scan options
722
* @returns AsyncIterator of field-value pairs
723
*/
724
hScanIterator(key: RedisArgument, options?: ScanOptions): AsyncIterableIterator<{ field: BlobStringReply; value: BlobStringReply }>;
725
726
/**
727
* Scan set members
728
* @param key - Set key
729
* @param options - Scan options
730
* @returns AsyncIterator of set members
731
*/
732
sScanIterator(key: RedisArgument, options?: ScanOptions): AsyncIterableIterator<BlobStringReply>;
733
734
/**
735
* Scan sorted set members
736
* @param key - Sorted set key
737
* @param options - Scan options
738
* @returns AsyncIterator of member-score pairs
739
*/
740
zScanIterator(key: RedisArgument, options?: ScanOptions): AsyncIterableIterator<{ value: BlobStringReply; score: number }>;
741
742
interface ScanOptions {
743
/** Pattern to match */
744
MATCH?: string;
745
/** Number of elements to return in each iteration */
746
COUNT?: number;
747
/** Type of keys to return */
748
TYPE?: string;
749
}
750
```
751
752
**Usage Examples:**
753
754
```typescript
755
// Iterate over all keys
756
for await (const key of client.scanIterator({ MATCH: "user:*" })) {
757
console.log("Key:", key);
758
}
759
760
// Iterate over hash fields
761
for await (const { field, value } of client.hScanIterator("user:123")) {
762
console.log(`${field}: ${value}`);
763
}
764
765
// Iterate over set members
766
for await (const member of client.sScanIterator("tags")) {
767
console.log("Member:", member);
768
}
769
770
// Iterate over sorted set with scores
771
for await (const { value, score } of client.zScanIterator("leaderboard")) {
772
console.log(`${value}: ${score}`);
773
}
774
```
775
776
### Pub/Sub Commands
777
778
Publish/Subscribe messaging pattern for real-time communication between Redis clients.
779
780
```typescript { .api }
781
/**
782
* Publish a message to a channel
783
* @param channel - The channel to publish to
784
* @param message - The message to publish
785
* @returns Number of subscribers that received the message
786
*/
787
publish(channel: RedisArgument, message: RedisArgument): Promise<NumberReply>;
788
PUBLISH(channel: RedisArgument, message: RedisArgument): Promise<NumberReply>;
789
790
/**
791
* Publish a message to a shard channel (Redis Cluster)
792
* @param channel - The shard channel to publish to
793
* @param message - The message to publish
794
* @returns Number of subscribers that received the message
795
*/
796
sPublish(channel: RedisArgument, message: RedisArgument): Promise<NumberReply>;
797
SPUBLISH(channel: RedisArgument, message: RedisArgument): Promise<NumberReply>;
798
799
/**
800
* Subscribe to one or more channels
801
* @param channels - Channel name(s) to subscribe to
802
* @param listener - Callback function for received messages
803
* @param bufferMode - Optional buffer mode flag
804
*/
805
subscribe<T extends boolean = false>(
806
channels: string | Array<string>,
807
listener: PubSubListener<T>,
808
bufferMode?: T
809
): Promise<void>;
810
SUBSCRIBE<T extends boolean = false>(
811
channels: string | Array<string>,
812
listener: PubSubListener<T>,
813
bufferMode?: T
814
): Promise<void>;
815
816
/**
817
* Unsubscribe from channels
818
* @param channels - Optional channel name(s) to unsubscribe from
819
* @param listener - Optional specific listener to remove
820
* @param bufferMode - Optional buffer mode flag
821
*/
822
unsubscribe<T extends boolean = false>(
823
channels?: string | Array<string>,
824
listener?: PubSubListener<T>,
825
bufferMode?: T
826
): Promise<void>;
827
UNSUBSCRIBE<T extends boolean = false>(
828
channels?: string | Array<string>,
829
listener?: PubSubListener<T>,
830
bufferMode?: T
831
): Promise<void>;
832
833
/**
834
* Subscribe to channels matching patterns
835
* @param patterns - Pattern(s) to subscribe to
836
* @param listener - Callback function for received messages
837
* @param bufferMode - Optional buffer mode flag
838
*/
839
pSubscribe<T extends boolean = false>(
840
patterns: string | Array<string>,
841
listener: PubSubListener<T>,
842
bufferMode?: T
843
): Promise<void>;
844
PSUBSCRIBE<T extends boolean = false>(
845
patterns: string | Array<string>,
846
listener: PubSubListener<T>,
847
bufferMode?: T
848
): Promise<void>;
849
850
/**
851
* Unsubscribe from pattern subscriptions
852
* @param patterns - Optional pattern(s) to unsubscribe from
853
* @param listener - Optional specific listener to remove
854
* @param bufferMode - Optional buffer mode flag
855
*/
856
pUnsubscribe<T extends boolean = false>(
857
patterns?: string | Array<string>,
858
listener?: PubSubListener<T>,
859
bufferMode?: T
860
): Promise<void>;
861
PUNSUBSCRIBE<T extends boolean = false>(
862
patterns?: string | Array<string>,
863
listener?: PubSubListener<T>,
864
bufferMode?: T
865
): Promise<void>;
866
867
/**
868
* Subscribe to shard channels (Redis Cluster)
869
* @param channels - Shard channel name(s) to subscribe to
870
* @param listener - Callback function for received messages
871
* @param bufferMode - Optional buffer mode flag
872
*/
873
sSubscribe<T extends boolean = false>(
874
channels: string | Array<string>,
875
listener: PubSubListener<T>,
876
bufferMode?: T
877
): Promise<void>;
878
SSUBSCRIBE<T extends boolean = false>(
879
channels: string | Array<string>,
880
listener: PubSubListener<T>,
881
bufferMode?: T
882
): Promise<void>;
883
884
/**
885
* Unsubscribe from shard channels
886
* @param channels - Optional shard channel name(s) to unsubscribe from
887
* @param listener - Optional specific listener to remove
888
* @param bufferMode - Optional buffer mode flag
889
*/
890
sUnsubscribe<T extends boolean = false>(
891
channels?: string | Array<string>,
892
listener?: PubSubListener<T>,
893
bufferMode?: T
894
): Promise<void>;
895
SUNSUBSCRIBE<T extends boolean = false>(
896
channels?: string | Array<string>,
897
listener?: PubSubListener<T>,
898
bufferMode?: T
899
): Promise<void>;
900
901
/**
902
* Get list of active channels
903
* @param pattern - Optional pattern to filter channels
904
* @returns List of active channels
905
*/
906
pubSubChannels(pattern?: RedisArgument): Promise<ArrayReply<BlobStringReply>>;
907
PUBSUB_CHANNELS(pattern?: RedisArgument): Promise<ArrayReply<BlobStringReply>>;
908
909
/**
910
* Get subscriber count for channels
911
* @param channels - Optional channel names to get subscription count for
912
* @returns Channel names mapped to subscriber counts
913
*/
914
pubSubNumSub(channels?: RedisVariadicArgument): Promise<Record<string, NumberReply>>;
915
PUBSUB_NUMSUB(channels?: RedisVariadicArgument): Promise<Record<string, NumberReply>>;
916
917
/**
918
* Get number of pattern subscriptions
919
* @returns Number of pattern subscriptions
920
*/
921
pubSubNumPat(): Promise<NumberReply>;
922
PUBSUB_NUMPAT(): Promise<NumberReply>;
923
924
/**
925
* Get list of active shard channels
926
* @param pattern - Optional pattern to filter shard channels
927
* @returns List of active shard channels
928
*/
929
pubSubShardChannels(pattern?: RedisArgument): Promise<ArrayReply<BlobStringReply>>;
930
PUBSUB_SHARDCHANNELS(pattern?: RedisArgument): Promise<ArrayReply<BlobStringReply>>;
931
932
/**
933
* Get subscriber count for shard channels
934
* @param channels - Optional shard channel names to get subscription count for
935
* @returns Shard channel names mapped to subscriber counts
936
*/
937
pubSubShardNumSub(channels?: RedisVariadicArgument): Promise<Record<string, NumberReply>>;
938
PUBSUB_SHARDNUMSUB(channels?: RedisVariadicArgument): Promise<Record<string, NumberReply>>;
939
940
// Pub/Sub listener type
941
type PubSubListener<T extends boolean = false> = (
942
message: T extends true ? Buffer : string,
943
channel: T extends true ? Buffer : string
944
) => unknown;
945
946
// Variadic argument type
947
type RedisVariadicArgument = RedisArgument | Array<RedisArgument>;
948
```
949
950
**Usage Examples:**
951
952
```typescript
953
import { createClient } from "redis";
954
955
const client = createClient();
956
await client.connect();
957
958
// Publishing messages
959
const subscriberCount = await client.publish("news", "Breaking news!");
960
console.log(`Message sent to ${subscriberCount} subscribers`);
961
962
// Shard publishing (for Redis Cluster)
963
await client.sPublish("events", "New event occurred");
964
965
// Subscribing to channels
966
await client.subscribe("news", (message, channel) => {
967
console.log(`Received message on ${channel}: ${message}`);
968
});
969
970
// Subscribing to multiple channels
971
await client.subscribe(["news", "updates", "alerts"], (message, channel) => {
972
console.log(`Channel ${channel}: ${message}`);
973
});
974
975
// Pattern subscriptions
976
await client.pSubscribe("news:*", (message, channel) => {
977
console.log(`Pattern match - ${channel}: ${message}`);
978
});
979
980
// Shard subscriptions (Redis Cluster)
981
await client.sSubscribe("cluster-events", (message, channel) => {
982
console.log(`Shard channel ${channel}: ${message}`);
983
});
984
985
// Buffer mode for binary data
986
await client.subscribe("binary-data", (message, channel) => {
987
console.log(`Binary message length: ${message.length}`);
988
}, true); // bufferMode = true
989
990
// Introspection commands
991
const activeChannels = await client.pubSubChannels();
992
console.log("Active channels:", activeChannels);
993
994
const channelStats = await client.pubSubNumSub(["news", "updates"]);
995
console.log("Subscriber counts:", channelStats);
996
997
const patternCount = await client.pubSubNumPat();
998
console.log("Active pattern subscriptions:", patternCount);
999
1000
// Unsubscribing
1001
await client.unsubscribe("news");
1002
await client.pUnsubscribe("news:*");
1003
await client.sUnsubscribe("cluster-events");
1004
```