README
Intro
A high performance Node.js Redis client. This package is derived from npm Node Redis and in this package Redis ACL functionalities are added.
Installation
npm install xredis
Usage
Example
const redis = require("xredis");
const client = redis.createClient();
client.on("error", function(error) {
console.error(error);
});
client.set("key", "value", redis.print);
client.get("key", redis.print);
Note that the API is entirely asynchronous. To get data back from the server, you'll need to use a callback.
Promises
Node Redis currently doesn't natively support promises (this is coming in v4), however you can wrap the methods you
want to use with promises using the built-in Node.js util.promisify
method on Node.js >= v8;
const { promisify } = require("util");
const getAsync = promisify(client.get).bind(client);
getAsync.then(console.log).catch(console.error);
Commands
This library is a 1 to 1 mapping of the Redis commands.
Each Redis command is exposed as a function on the client
object.
All functions take either an args
Array plus optional callback
Function or
a variable number of individual arguments followed by an optional callback.
Examples:
client.hmset(["key", "foo", "bar"], function(err, res) {
// ...
});
// Works the same as
client.hmset("key", ["foo", "bar"], function(err, res) {
// ...
});
// Or
client.hmset("key", "foo", "bar", function(err, res) {
// ...
});
Care should be taken with user input if arrays are possible (via body-parser, query string or other method), as single arguments could be unintentionally interpreted as multiple args.
Note that in either form the callback
is optional:
client.set("foo", "bar");
client.set(["hello", "world"]);
If the key is missing, reply will be null. Only if the Redis Command Reference states something else it will not be null.
client.get("missing_key", function(err, reply) {
// reply is null when the key is missing
console.log(reply);
});
Minimal parsing is done on the replies. Commands that return a integer return
JavaScript Numbers, arrays return JavaScript Array. HGETALL
returns an Object
keyed by the hash keys. All strings will either be returned as string or as
buffer depending on your setting. Please be aware that sending null, undefined
and Boolean values will result in the value coerced to a string!
API
Connection and other Events
client
will emit some events about the state of the connection to the Redis server.
"ready"
client
will emit ready
once a connection is established. Commands issued
before the ready
event are queued, then replayed just before this event is
emitted.
"connect"
client
will emit connect
as soon as the stream is connected to the server.
"reconnecting"
client
will emit reconnecting
when trying to reconnect to the Redis server
after losing the connection. Listeners are passed an object containing delay
(in ms from the previous try) and attempt
(the attempt #) attributes.
"error"
client
will emit error
when encountering an error connecting to the Redis
server or when any other in Node Redis occurs. If you use a command without
callback and encounter a ReplyError it is going to be emitted to the error
listener.
So please attach the error listener to Node Redis.
"end"
client
will emit end
when an established Redis server connection has closed.
"warning"
client
will emit warning
when password was set but none is needed and if a
deprecated option / function / similar is used.
redis.createClient()
If you have redis-server
running on the same machine as node, then the
defaults for port and host are probably fine and you don't need to supply any
arguments. createClient()
returns a RedisClient
object. Otherwise,
createClient()
accepts these arguments:
redis.createClient([options])
redis.createClient(unix_socket[, options])
redis.createClient(redis_url[, options])
redis.createClient(port[, host][, options])
Tip: If the Redis server runs on the same machine as the client consider using unix sockets if possible to increase throughput.
Note: Using 'rediss://...
for the protocol in a redis_url
will enable a TLS socket connection. However, additional TLS options will need to be passed in options
, if required.
object properties options
Property | Default | Description |
---|---|---|
host | 127.0.0.1 | IP address of the Redis server |
port | 6379 | Port of the Redis server |
path | null | The UNIX socket string of the Redis server |
url | null | The URL of the Redis server. Format: [redis[s]:]//[[user][:password@]][host][:port][/db-number][?db=db-number[&password=bar[&option=value]]] (More info avaliable at IANA). |
string_numbers | null | Set to true , Node Redis will return Redis number values as Strings instead of javascript Numbers. Useful if you need to handle big numbers (above Number.MAX_SAFE_INTEGER === 2^53 ). Hiredis is incapable of this behavior, so setting this option to true will result in the built-in javascript parser being used no matter the value of the parser option. |
return_buffers | false | If set to true , then all replies will be sent to callbacks as Buffers instead of Strings. |
detect_buffers | false | If set to true , then replies will be sent to callbacks as Buffers. This option lets you switch between Buffers and Strings on a per-command basis, whereas return_buffers applies to every command on a client. Note: This doesn't work properly with the pubsub mode. A subscriber has to either always return Strings or Buffers. |
socket_keepalive | true | If set to true , the keep-alive functionality is enabled on the underlying socket. |
socket_initial_delay | 0 | Initial Delay in milliseconds, and this will also behave the interval keep alive message sending to Redis. |
no_ready_check | false | When a connection is established to the Redis server, the server might still be loading the database from disk. While loading, the server will not respond to any commands. To work around this, Node Redis has a "ready check" which sends the INFO command to the server. The response from the INFO command indicates whether the server is ready for more commands. When ready, node_redis emits a ready event. Setting no_ready_check to true will inhibit this check. |
enable_offline_queue | true | By default, if there is no active connection to the Redis server, commands are added to a queue and are executed once the connection has been established. Setting enable_offline_queue to false will disable this feature and the callback will be executed immediately with an error, or an error will be emitted if no callback is specified. |
retry_unfulfilled_commands | false | If set to true , all commands that were unfulfilled while the connection is lost will be retried after the connection has been reestablished. Use this with caution if you use state altering commands (e.g. incr ). This is especially useful if you use blocking commands. |
password | null | If set, client will run Redis auth command on connect. Alias auth_pass Note Node Redis < 2.5 must use auth_pass |
db | null | If set, client will run Redis select command on connect. |
family | IPv4 | You can force using IPv6 if you set the family to 'IPv6'. See Node.js net or dns modules on how to use the family type. |
disable_resubscribing | false | If set to true , a client won't resubscribe after disconnecting. |
rename_commands | null | Passing an object with renamed commands to use instead of the original functions. For example, if you renamed the command KEYS to "DO-NOT-USE" then the rename_commands object would be: { KEYS : "DO-NOT-USE" } . See the Redis security topics for more info. |
tls | null | An object containing options to pass to tls.connect to set up a TLS connection to Redis (if, for example, it is set up to be accessible via a tunnel). |
prefix | null | A string used to prefix all used keys (e.g. namespace:test ). Please be aware that the keys command will not be prefixed. The keys command has a "pattern" as argument and no key and it would be impossible to determine the existing keys in Redis if this would be prefixed. |
retry_strategy | function | A function that receives an options object as parameter including the retry attempt , the total_retry_time indicating how much time passed since the last time connected, the error why the connection was lost and the number of times_connected in total. If you return a number from this function, the retry will happen exactly after that time in milliseconds. If you return a non-number, no further retry will happen and all offline commands are flushed with errors. Return an error to return that specific error to all offline commands. Example below. |
detect_buffers
example:
const redis = require("redis");
const client = redis.createClient({ detect_buffers: true });
client.set("foo_rand000000000000", "OK");
// This will return a JavaScript String
client.get("foo_rand000000000000", function(err, reply) {
console.log(reply.toString()); // Will print `OK`
});
// This will return a Buffer since original key is specified as a Buffer
client.get(new Buffer("foo_rand000000000000"), function(err, reply) {
console.log(reply.toString()); // Will print `<Buffer 4f 4b>`
});
retry_strategy
example:
const client = redis.createClient({
retry_strategy: function(options) {
if (options.error && options.error.code === "ECONNREFUSED") {
// End reconnecting on a specific error and flush all commands with
// a individual error
return new Error("The server refused the connection");
}
if (options.total_retry_time > 1000 * 60 * 60) {
// End reconnecting after a specific timeout and flush all commands
// with a individual error
return new Error("Retry time exhausted");
}
if (options.attempt > 10) {
// End reconnecting with built in error
return undefined;
}
// reconnect after
return Math.min(options.attempt * 100, 3000);
},
});
client.auth
When connecting to a Redis server as a default user that requires authentication, the AUTH
command must be sent as the first command after connecting. This can be tricky
to coordinate with reconnections, the ready check, etc. To make this easier,
client.auth()
stashes password
and will send it after each connection,
including reconnections. callback
is invoked only once, after the response to
the very first AUTH
command sent.
NOTE: Your call to client.auth()
should not be inside the ready handler. If
you are doing this wrong, client
will emit an error that looks
something like this Error: Ready check failed: ERR operation not permitted
.
For ACL user
client.auth('username','password',(callback))
For Default user
client.auth('password',(callback))
client.acl([],(callback))
In order to use ACL commands, put all the commands in an array and put the array in the first argument of the function and callback in the second argument.
// ACL SETUSER
client.acl(['setuser', 'someusername', 'on', 'nopass', '~*', '+@all', '-@dangerous'], function (err, succ) {
if (err) { console.error(err) }
if (succ) { console.log(succ) }
});
// ACL DELUSER
client.acl(['deluser', 'someusername'], function (err, succ){
if (err) { console.error(err) }
if (succ) { console.log(succ) }
});
Use other ACL commands in the same format, for more ACL rules visit https://redis.io/topics/acl
In order to kill ACl client 'CLIENT KILL USER username', Closes all the connections that are authenticated with the specified ACL username, however it returns an error if the username does not map to an existing ACL user.
client.client('KILL', 'USER', 'aclusername', function (err, succ){
if (err) { console.error(err) }
if (succ) { console.log(succ) }
});
client.quit(callback)
This sends the quit command to the redis server and ends cleanly right after all running commands were properly handled. If this is called while reconnecting (and therefore no connection to the redis server exists) it is going to end the connection right away instead of resulting in further reconnections! All offline commands are going to be flushed with an error in that case.
client.end(flush)
Forcibly close the connection to the Redis server. Note that this does not wait
until all replies have been parsed. If you want to exit cleanly, call
client.quit()
as mentioned above.
You should set flush to true, if you are not absolutely sure you do not care about any other commands. If you set flush to false all still running commands will silently fail.
This example closes the connection to the Redis server before the replies have been read. You probably don't want to do this:
const redis = require("redis");
const client = redis.createClient();
client.set("hello", "world", function(err) {
// This will either result in an error (flush parameter is set to true)
// or will silently fail and this callback will not be called at all (flush set to false)
console.error(err);
});
// No further commands will be processed
client.end(true);
client.get("hello", function(err) {
console.error(err); // => 'The connection has already been closed.'
});
client.end()
without the flush parameter set to true should NOT be used in production!
Error Handling
Currently the following Error
subclasses exist:
RedisError
: All errors returned by the clientReplyError
subclass ofRedisError
: All errors returned by Redis itselfAbortError
subclass ofRedisError
: All commands that could not finish due to what ever reasonParserError
subclass ofRedisError
: Returned in case of a parser error (this should not happen)AggregateError
subclass ofAbortError
: Emitted in case multiple unresolved commands without callback got rejected in debug_mode instead of lots ofAbortError
s.
All error classes are exported by the module.
Example
const assert = require("assert");
const redis = require("redis");
const { AbortError, AggregateError, ReplyError } = require("redis");
const client = redis.createClient();
client.on("error", function(err) {
assert(err instanceof Error);
assert(err instanceof AbortError);
assert(err instanceof AggregateError);
// The set and get are aggregated in here
assert.strictEqual(err.errors.length, 2);
assert.strictEqual(err.code, "NR_CLOSED");
});
client.set("foo", "bar", "baz", function(err, res) {
// Too many arguments
assert(err instanceof ReplyError); // => true
assert.strictEqual(err.command, "SET");
assert.deepStrictEqual(err.args, ["foo", 123, "bar"]);
redis.debug_mode = true;
client.set("foo", "bar");
client.get("foo");
process.nextTick(function() {
// Force closing the connection while the command did not yet return
client.end(true);
redis.debug_mode = false;
});
});
Every ReplyError
contains the command
name in all-caps and the arguments (args
).
If Node Redis emits a library error because of another error, the triggering
error is added to the returned error as origin
attribute.
Error codes
Node Redis returns a NR_CLOSED
error code if the clients connection dropped.
If a command unresolved command got rejected a UNCERTAIN_STATE
code is
returned. A CONNECTION_BROKEN
error code is used in case Node Redis gives up
to reconnect.
client.unref()
Call unref()
on the underlying socket connection to the Redis server, allowing
the program to exit once no more commands are pending.
This is an experimental feature, and only supports a subset of the Redis
protocol. Any commands where client state is saved on the Redis server, e.g.
*SUBSCRIBE
or the blocking BL*
commands will NOT work with .unref()
.
const redis = require("redis");
const client = redis.createClient();
/*
* Calling unref() will allow this program to exit immediately after the get
* command finishes. Otherwise the client would hang as long as the
* client-server connection is alive.
*/
client.unref();
client.get("foo", function(err, value) {
if (err) throw err;
console.log(value);
});
Hash Commands
Most Redis commands take a single String or an Array of Strings as arguments, and replies are sent back as a single String or an Array of Strings. When dealing with hash values, there are a couple of useful exceptions to this.
client.hgetall(hash, callback)
The reply from an HGETALL
command will be converted into a JavaScript Object. That way you can interact with the
responses using JavaScript syntax.
Example:
client.hmset("key", "foo", "bar", "hello", "world");
client.hgetall("hosts", function(err, value) {
console.log(value.foo); // > "bar"
console.log(value.hello); // > "world"
});
client.hmset(hash, key1, val1, ...keyN, valN, [callback])
Multiple values may also be set by supplying more arguments.
Example:
// key
// 1) foo => bar
// 2) hello => world
client.HMSET("key", "foo", "bar", "hello", "world");
PubSub
Example
This example opens two client connections, subscribes to a channel on one of them, and publishes to that channel on the other.
const redis = require("redis");
const subscriber = redis.createClient();
const publisher = redis.createClient();
let messageCount = 0;
subscriber.on("subscribe", function(channel, count) {
publisher.publish("a channel", "a message");
publisher.publish("a channel", "another message");
});
subscriber.on("message", function(channel, message) {
messageCount += 1;
console.log("Subscriber received message in channel '" + channel + "': " + message);
if (messageCount === 2) {
subscriber.unsubscribe();
subscriber.quit();
publisher.quit();
}
});
subscriber.subscribe("a channel");
When a client issues a SUBSCRIBE
or PSUBSCRIBE
, that connection is put into
a "subscriber"
mode. At that point, the only valid commands are those that modify the subscription
set, and quit (also ping on some redis versions). When
the subscription set is empty, the connection is put back into regular mode.
If you need to send regular commands to Redis while in subscriber mode, just
open another connection with a new client (use client.duplicate()
to quickly duplicate an existing client).
Subscriber Events
If a client has subscriptions active, it may emit these events:
"message" (channel, message):
Client will emit message
for every message received that matches an active subscription.
Listeners are passed the channel name as channel
and the message as message
.
"pmessage" (pattern, channel, message):
Client will emit pmessage
for every message received that matches an active
subscription pattern. Listeners are passed the original pattern used with
PSUBSCRIBE
as pattern
, the sending channel name as channel
, and the
message as message
.
"message_buffer" (channel, message):
This is the same as the message
event with the exception, that it is always
going to emit a buffer. If you listen to the message
event at the same time as
the message_buffer
, it is always going to emit a string.
"pmessage_buffer" (pattern, channel, message):
This is the same as the pmessage
event with the exception, that it is always
going to emit a buffer. If you listen to the pmessage
event at the same time
as the pmessage_buffer
, it is always going to emit a string.
"subscribe" (channel, count):
Client will emit subscribe
in response to a SUBSCRIBE
command. Listeners are
passed the channel name as channel
and the new count of subscriptions for this
client as count
.
"psubscribe" (pattern, count):
Client will emit psubscribe
in response to a PSUBSCRIBE
command. Listeners
are passed the original pattern as pattern
, and the new count of subscriptions
for this client as count
.
"unsubscribe" (channel, count):
Client will emit unsubscribe
in response to a UNSUBSCRIBE
command. Listeners
are passed the channel name as channel
and the new count of subscriptions for
this client as count
. When count
is 0, this client has left subscriber mode
and no more subscriber events will be emitted.
"punsubscribe" (pattern, count):
Client will emit punsubscribe
in response to a PUNSUBSCRIBE
command.
Listeners are passed the channel name as channel
and the new count of
subscriptions for this client as count
. When count
is 0, this client has
left subscriber mode and no more subscriber events will be emitted.
Streams
Example
// Add in to the stream
client.xadd('mystream', '*', 'field1', 'm1', function (err) {
if (err) {
return console.error(err);
}
});
// Read from stream
client.xread('COUNT', 2, 'STREAMS', 'mystream', 0, function (succ) {
if (succ) {
console.log(err);
}
});
// create group
client1.xgroup('CREATE', 'mystream', 'mygroup', '