- Notifications
You must be signed in to change notification settings - Fork1.9k
redis/node-redis
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
node-redis is a modern, high performanceRedis client for Node.js.
Learn for free at Redis University
Build faster with the Redis Launchpad
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.
Name | Description |
---|---|
redis | The client with all the"redis-stack" modules |
@redis/client | The base clients (i.eRedisClient ,RedisCluster , etc.) |
@redis/bloom | Redis Bloom commands |
@redis/json | Redis JSON commands |
@redis/search | RediSearch commands |
@redis/time-series | Redis Time-Series commands |
@redis/entraid | Secure token-based authentication for Redis clients using Microsoft Entra ID |
Looking for a high-level library to handle object mapping?Seeredis-om-node!
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).
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']
Buffer
s 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> }
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.
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.
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();
See thePub/Sub overview.
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,});
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();
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.
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=="),]);
See theProgrammability overview.
Check out theClustering Guide when using Node Redis to connect to a Redis Cluster.
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.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 | Seehere | Seehere |
invalidate | Client 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.
Node Redis is supported with the following versions of Redis:
Version | Supported |
---|---|
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.
If you'd like to contribute, check out thecontributing guide.
Thank you to all the people who already contributed to Node Redis!
This repository is licensed under the "MIT" license. SeeLICENSE.
About
Redis Node.js client
Topics
Resources
License
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.