API.md

June 11, 2019 · View on GitHub

Classes

Redis[EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter)
Cluster[EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter)
Commander

Redis ⇐ EventEmitter

Kind: global class
Extends: EventEmitter, Commander

new Redis([port], [host], [options])

Creates a Redis instance

ParamTypeDefaultDescription
[port]number | string | Object6379Port of the Redis server, or a URL string(see the examples below), or the options object(see the third argument).
[host]string | Object"localhost"Host of the Redis server, when the first argument is a URL string, this argument is an object represents the options.
[options]ObjectOther options.
[options.port]number6379Port of the Redis server.
[options.host]string"localhost"Host of the Redis server.
[options.family]string4Version of IP stack. Defaults to 4.
[options.path]stringnullLocal domain socket path. If set the port, host and family will be ignored.
[options.keepAlive]number0TCP KeepAlive on the socket with a X ms delay before start. Set to a non-number value to disable keepAlive.
[options.noDelay]booleantrueWhether to disable the Nagle's Algorithm. By default we disable it to reduce the latency.
[options.connectionName]stringnullConnection name.
[options.db]number0Database index to use.
[options.password]stringnullIf set, client will send AUTH command with the value of this option when connected.
[options.dropBufferSupport]booleanfalseDrop the buffer support for better performance. This option is recommended to be enabled when handling large array response and you don't need the buffer support.
[options.enableReadyCheck]booleantrueWhen a connection is established to the Redis server, the server might still be loading the database from disk. While loading, the server not respond to any commands. To work around this, when this option is true, ioredis will check the status of the Redis server, and when the Redis server is able to process commands, a ready event will be emitted.
[options.enableOfflineQueue]booleantrueBy default, if there is no active connection to the Redis server, commands are added to a queue and are executed once the connection is "ready" (when enableReadyCheck is true, "ready" means the Redis server has loaded the database from disk, otherwise means the connection to the Redis server has been established). If this option is false, when execute the command when the connection isn't ready, an error will be returned.
[options.connectTimeout]number10000The milliseconds before a timeout occurs during the initial connection to the Redis server.
[options.autoResubscribe]booleantrueAfter reconnected, if the previous connection was in the subscriber mode, client will auto re-subscribe these channels.
[options.autoResendUnfulfilledCommands]booleantrueIf true, client will resend unfulfilled commands(e.g. block commands) in the previous connection when reconnected.
[options.lazyConnect]booleanfalseBy default, When a new Redis instance is created, it will connect to Redis server automatically. If you want to keep the instance disconnected until a command is called, you can pass the lazyConnect option to the constructor: javascript var redis = new Redis({ lazyConnect: true }); // No attempting to connect to the Redis server here. // Now let's connect to the Redis server redis.get('foo', function () { });
[options.tls]ObjectTLS connection support. See https://github.com/luin/ioredis#tls-options
[options.keyPrefix]string"''"The prefix to prepend to all keys in a command.
[options.retryStrategy]functionSee "Quick Start" section
[options.maxRetriesPerRequest]numberSee "Quick Start" section
[options.reconnectOnError]functionSee "Quick Start" section
[options.readOnly]booleanfalseEnable READONLY mode for the connection. Only available for cluster mode.
[options.stringNumbers]booleanfalseForce numbers to be always returned as JavaScript strings. This option is necessary when dealing with big numbers (exceed the [-2532^{53}, +2532^{53}] range).

Example

var Redis = require('ioredis');

var redis = new Redis();

var redisOnPort6380 = new Redis(6380);
var anotherRedis = new Redis(6380, '192.168.100.1');
var unixSocketRedis = new Redis({ path: '/tmp/echo.sock' });
var unixSocketRedis2 = new Redis('/tmp/echo.sock');
var urlRedis = new Redis('redis://user:password@redis-service.com:6379/');
var urlRedis2 = new Redis('//localhost:6379');
var authedRedis = new Redis(6380, '192.168.100.1', { password: 'password' });

redis.connect([callback]) ⇒ Promise.<void>

Create a connection to Redis. This method will be invoked automatically when creating a new Redis instance unless lazyConnect: true is passed.

When calling this method manually, a Promise is returned, which will be resolved when the connection status is ready.

Kind: instance method of Redis
Access: public

ParamType
[callback]function

redis.disconnect()

Disconnect from Redis.

This method closes the connection immediately, and may lose some pending replies that haven't written to client. If you want to wait for the pending replies, use Redis#quit instead.

Kind: instance method of Redis
Access: public

redis.end()

Deprecated

Disconnect from Redis.

Kind: instance method of Redis

redis.duplicate()

Create a new instance with the same options as the current one.

Kind: instance method of Redis
Access: public
Example

var redis = new Redis(6380);
var anotherRedis = redis.duplicate();

redis.monitor([callback])

Listen for all requests received by the server in real time.

This command will create a new connection to Redis and send a MONITOR command via the new connection in order to avoid disturbing the current connection.

Kind: instance method of Redis
Access: public

ParamTypeDescription
[callback]functionThe callback function. If omit, a promise will be returned.

Example

var redis = new Redis();
redis.monitor(function (err, monitor) {
  // Entering monitoring mode.
  monitor.on('monitor', function (time, args, source, database) {
    console.log(time + ": " + util.inspect(args));
  });
});

// supports promise as well as other commands
redis.monitor().then(function (monitor) {
  monitor.on('monitor', function (time, args, source, database) {
    console.log(time + ": " + util.inspect(args));
  });
});

redis.getBuiltinCommands() ⇒ Array.<string>

Return supported builtin commands

Kind: instance method of Redis
Returns: Array.<string> - command list
Access: public

redis.createBuiltinCommand(commandName) ⇒ object

Create a builtin command

Kind: instance method of Redis
Returns: object - functions
Access: public

ParamTypeDescription
commandNamestringcommand name

redis.defineCommand(name, definition)

Define a custom command using lua script

Kind: instance method of Redis

ParamTypeDefaultDescription
namestringthe command name
definitionobject
definition.luastringthe lua code
[definition.numberOfKeys]numberthe number of keys. If omit, you have to pass the number of keys as the first argument every time you invoke the command

Redis.createClient()

Deprecated

Create a Redis instance

Kind: static method of Redis

Cluster ⇐ EventEmitter

Kind: global class
Extends: EventEmitter, Commander

new Cluster(startupNodes, options)

Creates a Redis Cluster instance

ParamTypeDefaultDescription
startupNodesArray.<Object>An array of nodes in the cluster, [{ port: number, host: string }]
optionsObject
[options.clusterRetryStrategy]functionSee "Quick Start" section
[options.dnsLookup]function(hostname, function(err, addr, family))dns.lookupFunction used to resolve DNS hostnames of Redis cluster members.
[options.enableOfflineQueue]booleantrueSee Redis class
[options.enableReadyCheck]booleantrueWhen enabled, ioredis only emits "ready" event when CLUSTER INFO command reporting the cluster is ready for handling commands.
[options.scaleReads]string"master"Scale reads to the node with the specified role. Available values are "master", "slave" and "all".
[options.maxRedirections]number16When a MOVED or ASK error is received, client will redirect the command to another node. This option limits the max redirections allowed to send a command.
[options.retryDelayOnFailover]number100When an error is received when sending a command(e.g. "Connection is closed." when the target Redis node is down),
[options.retryDelayOnClusterDown]number100When a CLUSTERDOWN error is received, client will retry if retryDelayOnClusterDown is valid delay time.
[options.retryDelayOnTryAgain]number100When a TRYAGAIN error is received, client will retry if retryDelayOnTryAgain is valid delay time.
[options.slotsRefreshTimeout]number1000The milliseconds before a timeout occurs while refreshing slots from the cluster.
[options.slotsRefreshInterval]number5000The milliseconds between every automatic slots refresh.
[options.redisOptions]ObjectPassed to the constructor of Redis.

cluster.connect() ⇒ Promise

Connect to a cluster

Kind: instance method of Cluster
Access: public

cluster.disconnect([reconnect])

Disconnect from every node in the cluster.

Kind: instance method of Cluster
Access: public

ParamType
[reconnect]boolean

cluster.quit([callback]) ⇒ Promise

Quit the cluster gracefully.

Kind: instance method of Cluster
Returns: Promise - return 'OK' if successfully
Access: public

ParamType
[callback]function

cluster.nodes([role]) ⇒ Array.<Redis>

Get nodes with the specified role

Kind: instance method of Cluster
Returns: Array.<Redis> - array of nodes
Access: public

ParamTypeDefaultDescription
[role]string"all"role, "master", "slave" or "all"

cluster.getBuiltinCommands() ⇒ Array.<string>

Return supported builtin commands

Kind: instance method of Cluster
Returns: Array.<string> - command list
Access: public

cluster.createBuiltinCommand(commandName) ⇒ object

Create a builtin command

Kind: instance method of Cluster
Returns: object - functions
Access: public

ParamTypeDescription
commandNamestringcommand name

cluster.defineCommand(name, definition)

Define a custom command using lua script

Kind: instance method of Cluster

ParamTypeDefaultDescription
namestringthe command name
definitionobject
definition.luastringthe lua code
[definition.numberOfKeys]numberthe number of keys. If omit, you have to pass the number of keys as the first argument every time you invoke the command

cluster.sendCommand()

Send a command

Kind: instance abstract method of Cluster
Overrides: sendCommand
Access: public

Commander

Kind: global class

new Commander()

Commander

This is the base class of Redis, Redis.Cluster and Pipeline

ParamTypeDefaultDescription
[options.showFriendlyErrorStack]booleanfalseWhether to show a friendly error stack. Will decrease the performance significantly.

commander.getBuiltinCommands() ⇒ Array.<string>

Return supported builtin commands

Kind: instance method of Commander
Returns: Array.<string> - command list
Access: public

commander.createBuiltinCommand(commandName) ⇒ object

Create a builtin command

Kind: instance method of Commander
Returns: object - functions
Access: public

ParamTypeDescription
commandNamestringcommand name

commander.defineCommand(name, definition)

Define a custom command using lua script

Kind: instance method of Commander

ParamTypeDefaultDescription
namestringthe command name
definitionobject
definition.luastringthe lua code
[definition.numberOfKeys]numberthe number of keys. If omit, you have to pass the number of keys as the first argument every time you invoke the command

commander.sendCommand()

Send a command

Kind: instance abstract method of Commander
Access: public