Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Redis Node.js client

License

NotificationsYou must be signed in to change notification settings

redis/node-redis

Repository files navigation

TestsCoverageLicense

DiscordTwitchYouTubeTwitter

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

How do I Redis?

Learn for free at Redis University

Build faster with the Redis Launchpad

Try the Redis Cloud

Dive in developer tutorials

Join the Redis community

Work at Redis

Installation

Start a redis via docker:

docker run -p 6379:6379 -d redis:8.0-rc1

To install node-redis, simply:

npm install redis

"redis" is the "whole in one" package that includes all the other packages. If you only need a subset of the commands,you can install the individual packages. See the list below.

Packages

NameDescription
redisThe client with all the"redis-stack" modules
@redis/clientThe base clients (i.eRedisClient,RedisCluster, etc.)
@redis/bloomRedis Bloom commands
@redis/jsonRedis JSON commands
@redis/searchRediSearch commands
@redis/time-seriesRedis Time-Series commands
@redis/entraidSecure token-based authentication for Redis clients using Microsoft Entra ID

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

Usage

Basic Example

import{createClient}from"redis";constclient=awaitcreateClient().on("error",(err)=>console.log("Redis Client Error",err)).connect();awaitclient.set("key","value");constvalue=awaitclient.get("key");client.destroy();

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

createClient({url:"redis://alice:foobared@awesome.redis.server:6380",});

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

To check if the the client is connected and ready to send commands, useclient.isReady which returns a boolean.client.isOpen is also available. This returnstrue when the client's underlying socket is open, andfalse when itisn'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 theout-of-the-box Redis commands. They are exposedusing the raw Redis command names (HSET,HGETALL, etc.) and a friendlier camel-cased version (hSet,hGetAll,etc.):

// raw Redis commandsawaitclient.HSET("key","field","value");awaitclient.HGETALL("key");// friendly JavaScript commandsawaitclient.hSet("key","field","value");awaitclient.hGetAll("key");

Modifiers to commands are specified using a JavaScript object:

awaitclient.set("key","value",{EX:10,NX:true,});

Replies will be transformed into useful data structures:

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

Buffers are supported as well:

constclient=createClient().withTypeMapping({[RESP_TYPES.BLOB_STRING]:Buffer});awaitclient.hSet("key","field",Buffer.from("value"));// 'OK'awaitclient.hGet("key","field");// { 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():

awaitclient.sendCommand(["SET","key","value","NX"]);// 'OK'awaitclient.sendCommand(["HGETALL","key"]);// ['key1', 'field1', 'key2', 'field2']

Note: theAPI is different when using a cluster.

Transactions (Multi/Exec)

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

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

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

Blocking Commands

In v4,RedisClient had the ability to create a pool of connections using an "Isolation Pool" on top of the "main"connection. However, there was no way to use the pool without a "main" connection:

constclient=awaitcreateClient().on("error",(err)=>console.error(err)).connect();awaitclient.ping(client.commandOptions({isolated:true}));

In v5 we've extracted this pool logic into its own class—RedisClientPool:

constpool=awaitcreateClientPool().on("error",(err)=>console.error(err)).connect();awaitpool.ping();

Pub/Sub

See thePub/Sub overview.

Scan Iterator

SCAN results can be looped overusingasync iterators:

forawait(constkeysofclient.scanIterator()){console.log(keys,awaitclient.mGet(keys));}

This works withHSCAN,SSCAN, andZSCAN too:

forawait(const{ field, value}ofclient.hScanIterator("hash")){}forawait(constmemberofclient.sScanIterator("set")){}forawait(const{ score, value}ofclient.zScanIterator("sorted-set")){}

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

client.scanIterator({TYPE:"string",// `SCAN` onlyMATCH:"patter*",COUNT:100,});

Disconnecting

TheQUIT command has been deprecated in Redis 7.2 and should now also be considered deprecated in Node-Redis. Insteadof sending aQUIT command to the server, the client can simply close the network connection.

client.QUIT/quit() is replaced byclient.close(). and, to avoid confusion,client.disconnect() has been renamed toclient.destroy().

client.destroy();

Client Side Caching

Node Redis v5 adds support forClient Side Caching, which enables clients to cache query results locally. The Redis server will notify the client when cached results are no longer valid.

// Enable client side caching with RESP3constclient=createClient({RESP:3,clientSideCache:{ttl:0,// Time-to-live (0 = no expiration)maxEntries:0,// Maximum entries (0 = unlimited)evictPolicy:"LRU"// Eviction policy: "LRU" or "FIFO"}});

See theV5 documentation for more details and advanced usage.

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 togetunhandled Promise exceptions. To takeadvantage of auto-pipelining and handle your Promises, usePromise.all().

awaitPromise.all([client.set("Tm9kZSBSZWRpcw==","users:1"),client.sAdd("users:1:tokens","Tm9kZSBSZWRpcw=="),]);

Programmability

See theProgrammability overview.

Clustering

Check out theClustering 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:

NameWhenListener arguments
connectInitiating a connection to the serverNo arguments
readyClient is ready to useNo arguments
endConnection has been closed (via.disconnect())No arguments
errorAn error has occurred—usually a network issue such as "Socket closed unexpectedly"(error: Error)
reconnectingClient is trying to reconnect to the serverNo arguments
sharded-channel-movedSeehereSeehere
invalidateClient Tracking is on withemitInvalidate and a key is invalidated(key: RedisItem | null)

⚠️ YouMUST listen toerror events. If a client doesn't have at least oneerror listener registered andanerror occurs, that error will be thrown and the Node.js process will exit. See the >EventEmitter docs for more details.

The client will not emitany other events beyond those listed above.

Supported Redis versions

Node Redis is supported with the following versions of Redis:

VersionSupported
8.2.z✔️
8.0.z✔️
7.4.z✔️
7.2.z✔️
< 7.2

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

Migration

Contributing

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

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

Contributors

License

This repository is licensed under the "MIT" license. SeeLICENSE.


[8]ページ先頭

©2009-2025 Movatter.jp