• Stars
    star
    16,841
  • Rank 1,642 (Top 0.04 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 14 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Redis Node.js client

Node-Redis

Tests Coverage License

Discord Twitch YouTube Twitter

node-redis is a modern, high performance Redis client for Node.js.

Packages

Name Description
redis Downloads Version
@redis/client Downloads Version Docs
@redis/bloom Downloads Version Docs Redis Bloom commands
@redis/graph Downloads Version Docs Redis Graph commands
@redis/json Downloads Version Docs Redis JSON commands
@redis/search Downloads Version Docs RediSearch commands
@redis/time-series Downloads Version Docs Redis Time-Series commands

โš ๏ธ In version 4.1.0 we moved our subpackages from @node-redis to @redis. If you're just using npm install redis, you don't need to do anythingโ€”it'll upgrade automatically. If you're using the subpackages directly, you'll need to point to the new scope (e.g. @redis/client instead of @node-redis/client).

Installation

Start a redis via docker:

docker run -p 6379:6379 -it redis/redis-stack-server:latest

To install node-redis, simply:

npm install redis

โš ๏ธ The new interface is clean and cool, but if you have an existing codebase, you'll want to read the migration guide.

Looking for a high-level library to handle object mapping? See redis-om-node!

Usage

Basic Example

import { createClient } from 'redis';

const client = createClient();

client.on('error', err => console.log('Redis Client Error', err));

await client.connect();

await client.set('key', 'value');
const value = await client.get('key');
await client.disconnect();

The above code connects to localhost on port 6379. To connect to a different host or port, use a connection string in the format redis[s]://[[username][:password]@][host][:port][/db-number]:

createClient({
  url: 'redis://alice:[email protected]:6380'
});

You can also use discrete parameters, UNIX sockets, and even TLS to connect. Details can be found in the client configuration guide.

To check if the the client is connected and ready to send commands, use client.isReady which returns a boolean. client.isOpen is also available. This returns true when the client's underlying socket is open, and false when it isn't (for example when the client is still connecting or reconnecting after a network error).

Redis Commands

There is built-in support for all of the out-of-the-box Redis commands. They are exposed using the raw Redis command names (HSET, HGETALL, etc.) and a friendlier camel-cased version (hSet, hGetAll, etc.):

// raw Redis commands
await client.HSET('key', 'field', 'value');
await client.HGETALL('key');

// friendly JavaScript commands
await client.hSet('key', 'field', 'value');
await client.hGetAll('key');

Modifiers to commands are specified using a JavaScript object:

await client.set('key', 'value', {
  EX: 10,
  NX: true
});

Replies will be transformed into useful data structures:

await client.hGetAll('key'); // { field1: 'value1', field2: 'value2' }
await client.hVals('key'); // ['value1', 'value2']

Buffers are supported as well:

await client.hSet('key', 'field', Buffer.from('value')); // 'OK'
await client.hGetAll(
  commandOptions({ returnBuffers: true }),
  'key'
); // { field: <Buffer 76 61 6c 75 65> }

Unsupported Redis Commands

If you want to run commands and/or use arguments that Node Redis doesn't know about (yet!) use .sendCommand():

await client.sendCommand(['SET', 'key', 'value', 'NX']); // 'OK'

await client.sendCommand(['HGETALL', 'key']); // ['key1', 'field1', 'key2', 'field2']

Transactions (Multi/Exec)

Start a transaction by calling .multi(), then chaining your commands. When you're done, call .exec() and you'll get an array back with your results:

await client.set('another-key', 'another-value');

const [setKeyReply, otherKeyValue] = await client
  .multi()
  .set('key', 'value')
  .get('another-key')
  .exec(); // ['OK', 'another-value']

You can also watch keys by calling .watch(). Your transaction will abort if any of the watched keys change.

To dig deeper into transactions, check out the Isolated Execution Guide.

Blocking Commands

Any command can be run on a new connection by specifying the isolated option. The newly created connection is closed when the command's Promise is fulfilled.

This pattern works especially well for blocking commandsโ€”such as BLPOP and BLMOVE:

import { commandOptions } from 'redis';

const blPopPromise = client.blPop(
  commandOptions({ isolated: true }),
  'key',
  0
);

await client.lPush('key', ['1', '2']);

await blPopPromise; // '2'

To learn more about isolated execution, check out the guide.

Pub/Sub

See the Pub/Sub overview.

Scan Iterator

SCAN results can be looped over using async iterators:

for await (const key of client.scanIterator()) {
  // use the key!
  await client.get(key);
}

This works with HSCAN, SSCAN, and ZSCAN too:

for await (const { field, value } of client.hScanIterator('hash')) {}
for await (const member of client.sScanIterator('set')) {}
for await (const { score, value } of client.zScanIterator('sorted-set')) {}

You can override the default options by providing a configuration object:

client.scanIterator({
  TYPE: 'string', // `SCAN` only
  MATCH: 'patter*',
  COUNT: 100
});

Programmability

Redis provides a programming interface allowing code execution on the redis server.

Functions

The following example retrieves a key in redis, returning the value of the key, incremented by an integer. For example, if your key foo has the value 17 and we run add('foo', 25), it returns the answer to Life, the Universe and Everything.

#!lua name=library

redis.register_function {
  function_name = 'add',
  callback = function(keys, args) return redis.call('GET', keys[1]) + args[1] end,
  flags = { 'no-writes' }
}

Here is the same example, but in a format that can be pasted into the redis-cli.

FUNCTION LOAD "#!lua name=library\nredis.register_function{function_name=\"add\", callback=function(keys, args) return redis.call('GET', keys[1])+args[1] end, flags={\"no-writes\"}}"

Load the prior redis function on the redis server before running the example below.

import { createClient } from 'redis';

const client = createClient({
  functions: {
    library: {
      add: {
        NUMBER_OF_KEYS: 1,
        transformArguments(key: string, toAdd: number): Array<string> {
          return [key, toAdd.toString()];
        },
        transformReply(reply: number): number {
          return reply;
        }
      }
    }
  }
});

await client.connect();

await client.set('key', '1');
await client.library.add('key', 2); // 3

Lua Scripts

The following is an end-to-end example of the prior concept.

import { createClient, defineScript } from 'redis';

const client = createClient({
  scripts: {
    add: defineScript({
      NUMBER_OF_KEYS: 1,
      SCRIPT:
        'return redis.call("GET", KEYS[1]) + ARGV[1];',
      transformArguments(key: string, toAdd: number): Array<string> {
        return [key, toAdd.toString()];
      },
      transformReply(reply: number): number {
        return reply;
      }
    })
  }
});

await client.connect();

await client.set('key', '1');
await client.add('key', 2); // 3

Disconnecting

There are two functions that disconnect a client from the Redis server. In most scenarios you should use .quit() to ensure that pending commands are sent to Redis before closing a connection.

.QUIT()/.quit()

Gracefully close a client's connection to Redis, by sending the QUIT command to the server. Before quitting, the client executes any remaining commands in its queue, and will receive replies from Redis for each of them.

const [ping, get, quit] = await Promise.all([
  client.ping(),
  client.get('key'),
  client.quit()
]); // ['PONG', null, 'OK']

try {
  await client.get('key');
} catch (err) {
  // ClosedClient Error
}

.disconnect()

Forcibly close a client's connection to Redis immediately. Calling disconnect will not send further pending commands to the Redis server, or wait for or parse outstanding responses.

await client.disconnect();

Auto-Pipelining

Node Redis will automatically pipeline requests that are made during the same "tick".

client.set('Tm9kZSBSZWRpcw==', 'users:1');
client.sAdd('users:1:tokens', 'Tm9kZSBSZWRpcw==');

Of course, if you don't do something with your Promises you're certain to get unhandled Promise exceptions. To take advantage of auto-pipelining and handle your Promises, use Promise.all().

await Promise.all([
  client.set('Tm9kZSBSZWRpcw==', 'users:1'),
  client.sAdd('users:1:tokens', 'Tm9kZSBSZWRpcw==')
]);

Clustering

Check out the Clustering Guide when using Node Redis to connect to a Redis Cluster.

Events

The Node Redis client class is an Nodejs EventEmitter and it emits an event each time the network status changes:

Name When Listener arguments
connect Initiating a connection to the server No arguments
ready Client is ready to use No arguments
end Connection has been closed (via .quit() or .disconnect()) No arguments
error An error has occurredโ€”usually a network issue such as "Socket closed unexpectedly" (error: Error)
reconnecting Client is trying to reconnect to the server No arguments
sharded-channel-moved See here See here

โš ๏ธ You MUST listen to error events. If a client doesn't have at least one error listener registered and an error occurs, that error will be thrown and the Node.js process will exit. See the EventEmitter docs for more details.

The client will not emit any other events beyond those listed above.

Supported Redis versions

Node Redis is supported with the following versions of Redis:

Version Supported
7.0.z โœ”๏ธ
6.2.z โœ”๏ธ
6.0.z โœ”๏ธ
5.0.z โœ”๏ธ
< 5.0 โŒ

Node Redis should work with older versions of Redis, but it is not fully tested and we cannot offer support.

Contributing

If you'd like to contribute, check out the contributing guide.

Thank you to all the people who already contributed to Node Redis!

Contributors

License

This repository is licensed under the "MIT" license. See LICENSE.

More Repositories

1

redis

Redis is an in-memory database that persists on disk. The data model is key-value, but many different kind of values are supported: Strings, Lists, Sets, Sorted Sets, Hashes, Streams, HyperLogLogs, Bitmaps.
C
66,875
star
2

go-redis

Redis Go client
Go
19,891
star
3

ioredis

๐Ÿš€ A robust, performance-focused, and full-featured Redis client for Node.js.
TypeScript
14,344
star
4

redis-py

Redis Python client
Python
12,506
star
5

jedis

Redis Java client
Java
11,766
star
6

hiredis

Minimalistic C client for Redis >= 1.2
C
6,197
star
7

lettuce

Advanced Java Redis client for thread-safe sync, async, and reactive usage. Supports Cluster, Sentinel, Pipelining, and codecs.
Java
5,352
star
8

redis-rb

A Ruby client library for Redis
Ruby
3,963
star
9

rueidis

A fast Golang Redis client that supports Client Side Caching, Auto Pipelining, Generics OM, RedisJSON, RedisBloom, RediSearch, etc.
Go
2,327
star
10

redis-doc

Redis documentation source code for markdown and metadata files, conversion scripts, and so forth
Shell
2,310
star
11

redis-om-node

Object mapping, and more, for Redis and Node.js. Written in TypeScript.
TypeScript
1,158
star
12

docker-library-redis

Docker Official Image packaging for Redis
Shell
1,117
star
13

redis-om-python

Object mapping, and more, for Redis and Python
Python
1,093
star
14

redis-io

Application running http://redis.io
Ruby
637
star
15

redis-om-spring

Spring Data Redis extensions for better search, documents models, and more
Java
599
star
16

hiredis-py

Python wrapper for hiredis
C
495
star
17

redis-om-dotnet

Object mapping, and more, for Redis and .NET
C#
457
star
18

hiredis-rb

Ruby wrapper for hiredis
Ruby
319
star
19

hiredis-node

Node wrapper for hiredis
JavaScript
305
star
20

riot

๐Ÿงจ Get data in & out of Redis with RIOT
Java
273
star
21

NRedisStack

Redis Stack .Net client
C#
220
star
22

redis-vl-python

Redis Vector Library (RedisVL) interfaces with Redis' vector database for realtime semantic search, RAG, and recommendation systems.
Python
218
star
23

redis-rcp

Redis Change Proposals
136
star
24

redis-hashes

Redis tarball SHA1 hashes
92
star
25

lettucemod

Java client for Redis Modules
Java
50
star
26

spring-batch-redis

Spring Batch extension for Redis
Java
47
star
27

redis-specifications

A bin for Redis' specs
38
star
28

minipilot

MiniPilot is a GenAI-assisted chatbot backed by Redis. Chat with your documents
HTML
31
star
29

redis-benchmarks-specification

The Redis benchmarks specification describes the cross-language/tools requirements and expectations to foster performance and observability standards around redis related technologies. Members from both industry and academia, including organizations and individuals are encouraged to contribute.
Python
29
star
30

librdb

Redis RDB file parser, with JSON, RESP and RDB-loader extensions
C
23
star
31

docs

Documentation for Redis, Redis Cloud, and Redis Enterprise
Python
23
star
32

redis-debian

Debian packaging
Shell
18
star
33

redis-snap

A repository for snap packaging
10
star
34

redis-website

HTML
9
star
35

Redis-Insight-Guides

Learn modern data models and data processing tools bundled in Redis Stack to build real-time applications with the speed and stability of Redis.
5
star
36

redis-clinterwebz

Python
4
star
37

redis-extra-ci

4
star
38

riot-docker

Dockerfile
2
star
39

redis-rpm

Shell
2
star
40

scoop

1
star
41

homebrew-tap

Homebrew tap for Redis organization
Ruby
1
star