Gathering detailed insights and metrics for redis
Gathering detailed insights and metrics for redis
Gathering detailed insights and metrics for redis
Gathering detailed insights and metrics for redis
redis-errors
Error classes used in node_redis
redis-parser
Javascript Redis protocol (RESP) parser
@redis/client
The source code and documentation for this package are in the main [node-redis](https://github.com/redis/node-redis) repo.
redis-commands
Redis commands implemented in javascript (learning purpose only)
npm install redis
Typescript
Module System
Node Version
NPM Version
99.2
Supply Chain
100
Quality
87.4
Maintenance
100
Vulnerability
100
License
redis@5.0.0-next.5
Published on 15 Oct 2024
redis@4.7.0
Published on 29 Jul 2024
client@1.6.0
Published on 29 Jul 2024
time-series@1.1.0
Published on 29 Jul 2024
search@1.2.0
Published on 29 Jul 2024
json@1.0.7
Published on 29 Jul 2024
Updated on 06 Dec 2024
Minified
Minified + Gzipped
TypeScript (99.28%)
JavaScript (0.71%)
Dockerfile (0.01%)
Cumulative downloads
Total Downloads
Last day
16%
Compared to previous day
Last week
1.9%
Compared to previous week
Last month
5.4%
Compared to previous month
Last year
16.1%
Compared to previous year
node-redis is a modern, high performance Redis client for Node.js.
Learn for free at Redis University
Build faster with the Redis Launchpad
Name | Description |
---|---|
redis | |
@redis/client | |
@redis/bloom | Redis Bloom commands |
@redis/graph | Redis Graph commands |
@redis/json | Redis JSON commands |
@redis/search | RediSearch commands |
@redis/time-series | Redis Time-Series commands |
:warning: In version 4.1.0 we moved our subpackages from
@node-redis
to@redis
. If you're just usingnpm 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
).
Start a redis via docker:
1docker run -p 6379:6379 -it redis/redis-stack-server:latest
To install node-redis, simply:
1npm install redis
:warning: 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!
1import { createClient } from 'redis'; 2 3const client = await createClient() 4 .on('error', err => console.log('Redis Client Error', err)) 5 .connect(); 6 7await client.set('key', 'value'); 8const value = await client.get('key'); 9await 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]
:
1createClient({ 2 url: 'redis://alice:foobared@awesome.redis.server:6380' 3});
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).
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.):
1// raw Redis commands 2await client.HSET('key', 'field', 'value'); 3await client.HGETALL('key'); 4 5// friendly JavaScript commands 6await client.hSet('key', 'field', 'value'); 7await client.hGetAll('key');
Modifiers to commands are specified using a JavaScript object:
1await client.set('key', 'value', { 2 EX: 10, 3 NX: true 4});
Replies will be transformed into useful data structures:
1await client.hGetAll('key'); // { field1: 'value1', field2: 'value2' } 2await client.hVals('key'); // ['value1', 'value2']
Buffer
s are supported as well:
1await client.hSet('key', 'field', Buffer.from('value')); // 'OK' 2await client.hGetAll( 3 commandOptions({ returnBuffers: true }), 4 'key' 5); // { 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()
:
1await client.sendCommand(['SET', 'key', 'value', 'NX']); // 'OK' 2 3await client.sendCommand(['HGETALL', 'key']); // ['key1', 'field1', 'key2', 'field2']
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:
1await client.set('another-key', 'another-value'); 2 3const [setKeyReply, otherKeyValue] = await client 4 .multi() 5 .set('key', 'value') 6 .get('another-key') 7 .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.
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
:
1import { commandOptions } from 'redis'; 2 3const blPopPromise = client.blPop( 4 commandOptions({ isolated: true }), 5 'key', 6 0 7); 8 9await client.lPush('key', ['1', '2']); 10 11await blPopPromise; // '2'
To learn more about isolated execution, check out the guide.
See the Pub/Sub overview.
SCAN
results can be looped over using async iterators:
1for await (const key of client.scanIterator()) { 2 // use the key! 3 await client.get(key); 4}
This works with HSCAN
, SSCAN
, and ZSCAN
too:
1for await (const { field, value } of client.hScanIterator('hash')) {} 2for await (const member of client.sScanIterator('set')) {} 3for await (const { score, value } of client.zScanIterator('sorted-set')) {}
You can override the default options by providing a configuration object:
1client.scanIterator({ 2 TYPE: 'string', // `SCAN` only 3 MATCH: 'patter*', 4 COUNT: 100 5});
Redis provides a programming interface allowing code execution on the redis server.
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.
1#!lua name=library 2 3redis.register_function { 4 function_name = 'add', 5 callback = function(keys, args) return redis.call('GET', keys[1]) + args[1] end, 6 flags = { 'no-writes' } 7}
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.
1import { createClient } from 'redis'; 2 3const client = createClient({ 4 functions: { 5 library: { 6 add: { 7 NUMBER_OF_KEYS: 1, 8 transformArguments(key: string, toAdd: number): Array<string> { 9 return [key, toAdd.toString()]; 10 }, 11 transformReply(reply: number): number { 12 return reply; 13 } 14 } 15 } 16 } 17}); 18 19await client.connect(); 20 21await client.set('key', '1'); 22await client.library.add('key', 2); // 3
The following is an end-to-end example of the prior concept.
1import { createClient, defineScript } from 'redis'; 2 3const client = createClient({ 4 scripts: { 5 add: defineScript({ 6 NUMBER_OF_KEYS: 1, 7 SCRIPT: 8 'return redis.call("GET", KEYS[1]) + ARGV[1];', 9 transformArguments(key: string, toAdd: number): Array<string> { 10 return [key, toAdd.toString()]; 11 }, 12 transformReply(reply: number): number { 13 return reply; 14 } 15 }) 16 } 17}); 18 19await client.connect(); 20 21await client.set('key', '1'); 22await client.add('key', 2); // 3
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.
1const [ping, get, quit] = await Promise.all([ 2 client.ping(), 3 client.get('key'), 4 client.quit() 5]); // ['PONG', null, 'OK'] 6 7try { 8 await client.get('key'); 9} catch (err) { 10 // ClosedClient Error 11}
.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.
1await client.disconnect();
Node Redis will automatically pipeline requests that are made during the same "tick".
1client.set('Tm9kZSBSZWRpcw==', 'users:1'); 2client.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()
.
1await Promise.all([ 2 client.set('Tm9kZSBSZWRpcw==', 'users:1'), 3 client.sAdd('users:1:tokens', 'Tm9kZSBSZWRpcw==') 4]);
Check out the Clustering 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 .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 |
:warning: You MUST listen to
error
events. If a client doesn't have at least oneerror
listener registered and anerror
occurs, that error will be thrown and the Node.js process will exit. See theEventEmitter
docs for more details.
The client will not emit any other events beyond those listed above.
Node Redis is supported with the following versions of Redis:
Version | Supported |
---|---|
7.0.z | :heavy_check_mark: |
6.2.z | :heavy_check_mark: |
6.0.z | :heavy_check_mark: |
5.0.z | :heavy_check_mark: |
< 5.0 | :x: |
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 the contributing guide.
Thank you to all the people who already contributed to Node Redis!
This repository is licensed under the "MIT" license. See LICENSE.
Stable Version
1
7.5/10
Summary
Node-Redis potential exponential regex in monitor mode
Affected Versions
>= 2.6.0, < 3.1.1
Patched Versions
3.1.1
Reason
21 commit(s) and 3 issue activity found in the last 90 days -- score normalized to 10
Reason
security policy file detected
Details
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
SAST tool detected but not run on all commits
Details
Reason
6 existing vulnerabilities detected
Details
Reason
Found 7/23 approved changesets -- score normalized to 3
Reason
dependency not pinned by hash detected -- score normalized to 2
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More