1 redis - a node.js redis client
2 ===========================
4 This is a complete Redis client for node.js. It supports all Redis commands, including many recently added commands like EVAL from
5 experimental Redis server branches.
12 Pieter Noordhuis has provided a binding to the official `hiredis` C library, which is non-blocking and fast. To use `hiredis`, do:
14 npm install hiredis redis
16 If `hiredis` is installed, `node_redis` will use it by default. Otherwise, a pure JavaScript parser will be used.
18 If you use `hiredis`, be sure to rebuild it whenever you upgrade your version of node. There are mysterious failures that can
19 happen between node and native code modules after a node upgrade.
24 Simple example, included as `examples/simple.js`:
27 var redis = require("redis"),
28 client = redis.createClient();
30 // if you'd like to select database 3, instead of 0 (default), call
31 // client.select(3, function() { /* ... */ });
33 client.on("error", function (err) {
34 console.log("Error " + err);
37 client.set("string key", "string val", redis.print);
38 client.hset("hash key", "hashtest 1", "some value", redis.print);
39 client.hset(["hash key", "hashtest 2", "some other value"], redis.print);
40 client.hkeys("hash key", function (err, replies) {
41 console.log(replies.length + " replies:");
42 replies.forEach(function (reply, i) {
43 console.log(" " + i + ": " + reply);
51 mjr:~/work/node_redis (master)$ node example.js
58 mjr:~/work/node_redis (master)$
63 Here are typical results of `multi_bench.js` which is similar to `redis-benchmark` from the Redis distribution.
64 It uses 50 concurrent connections with no pipelining.
68 PING: 20000 ops 42283.30 ops/sec 0/5/1.182
69 SET: 20000 ops 32948.93 ops/sec 1/7/1.515
70 GET: 20000 ops 28694.40 ops/sec 0/9/1.740
71 INCR: 20000 ops 39370.08 ops/sec 0/8/1.269
72 LPUSH: 20000 ops 36429.87 ops/sec 0/8/1.370
73 LRANGE (10 elements): 20000 ops 9891.20 ops/sec 1/9/5.048
74 LRANGE (100 elements): 20000 ops 1384.56 ops/sec 10/91/36.072
78 PING: 20000 ops 46189.38 ops/sec 1/4/1.082
79 SET: 20000 ops 41237.11 ops/sec 0/6/1.210
80 GET: 20000 ops 39682.54 ops/sec 1/7/1.257
81 INCR: 20000 ops 40080.16 ops/sec 0/8/1.242
82 LPUSH: 20000 ops 41152.26 ops/sec 0/3/1.212
83 LRANGE (10 elements): 20000 ops 36563.07 ops/sec 1/8/1.363
84 LRANGE (100 elements): 20000 ops 21834.06 ops/sec 0/9/2.287
86 The performance of `node_redis` improves dramatically with pipelining, which happens automatically in most normal programs.
91 Each Redis command is exposed as a function on the `client` object.
92 All functions take either an `args` Array plus optional `callback` Function or
93 a variable number of individual arguments followed by an optional callback.
94 Here is an example of passing an array of arguments and a callback:
96 client.mset(["test keys 1", "test val 1", "test keys 2", "test val 2"], function (err, res) {});
98 Here is that same call in the second style:
100 client.mset("test keys 1", "test val 1", "test keys 2", "test val 2", function (err, res) {});
102 Note that in either form the `callback` is optional:
104 client.set("some key", "some val");
105 client.set(["some other key", "some val"]);
107 If the key is missing, reply will be null (probably):
109 client.get("missingkey", function(err, reply) {
110 // reply is null when the key is missing
114 For a list of Redis commands, see [Redis Command Reference](http://redis.io/commands)
116 The commands can be specified in uppercase or lowercase for convenience. `client.get()` is the same as `client.GET()`.
118 Minimal parsing is done on the replies. Commands that return a single line reply return JavaScript Strings,
119 integer replies return JavaScript Numbers, "bulk" replies return node Buffers, and "multi bulk" replies return a
120 JavaScript Array of node Buffers. `HGETALL` returns an Object with Buffers keyed by the hash keys.
126 `client` will emit some events about the state of the connection to the Redis server.
130 `client` will emit `ready` a connection is established to the Redis server and the server reports
131 that it is ready to receive commands. Commands issued before the `ready` event are queued,
132 then replayed just before this event is emitted.
136 `client` will emit `connect` at the same time as it emits `ready` unless `client.options.no_ready_check`
137 is set. If this options is set, `connect` will be emitted when the stream is connected, and then
138 you are free to try to send commands.
142 `client` will emit `error` when encountering an error connecting to the Redis server.
144 Note that "error" is a special event type in node. If there are no listeners for an
145 "error" event, node will exit. This is usually what you want, but it can lead to some
146 cryptic error messages like this:
148 mjr:~/work/node_redis (master)$ node example.js
153 Error: ECONNREFUSED, Connection refused
154 at IOWatcher.callback (net:870:22)
157 Not very useful in diagnosing the problem, but if your program isn't ready to handle this,
158 it is probably the right thing to just exit.
160 `client` will also emit `error` if an exception is thrown inside of `node_redis` for whatever reason.
161 It would be nice to distinguish these two cases.
165 `client` will emit `end` when an established Redis server connection has closed.
169 `client` will emit `drain` when the TCP connection to the Redis server has been buffering, but is now
170 writable. This event can be used to stream commands in to Redis and adapt to backpressure. Right now,
171 you need to check `client.command_queue.length` to decide when to reduce your send rate. Then you can
172 resume sending when you get `drain`.
176 `client` will emit `idle` when there are no outstanding commands that are awaiting a response.
178 ## redis.createClient(port, host, options)
180 Create a new client connection. `port` defaults to `6379` and `host` defaults
181 to `127.0.0.1`. If you have `redis-server` running on the same computer as node, then the defaults for
182 port and host are probably fine. `options` in an object with the following possible properties:
184 * `parser`: which Redis protocol reply parser to use. Defaults to `hiredis` if that module is installed.
185 This may also be set to `javascript`.
186 * `return_buffers`: defaults to `false`. If set to `true`, then all replies will be sent to callbacks as node Buffer
187 objects instead of JavaScript Strings.
188 * `detect_buffers`: default to `false`. If set to `true`, then replies will be sent to callbacks as node Buffer objects
189 if any of the input arguments to the original command were Buffer objects.
190 This option lets you switch between Buffers and Strings on a per-command basis, whereas `return_buffers` applies to
191 every command on a client.
192 * `socket_nodelay`: defaults to `true`. Whether to call setNoDelay() on the TCP stream, which disables the
193 Nagle algorithm on the underlying socket. Setting this option to `false` can result in additional throughput at the
194 cost of more latency. Most applications will want this set to `true`.
195 * `no_ready_check`: defaults to `false`. When a connection is established to the Redis server, the server might still
196 be loading the database from disk. While loading, the server not respond to any commands. To work around this,
197 `node_redis` has a "ready check" which sends the `INFO` command to the server. The response from the `INFO` command
198 indicates whether the server is ready for more commands. When ready, `node_redis` emits a `ready` event.
199 Setting `no_ready_check` to `true` will inhibit this check.
200 * `enable_offline_queue`: defaults to `true`. By default, if there is no active
201 connection to the redis server, commands are added to a queue and are executed
202 once the connection has been established. Setting `enable_offline_queue` to
203 `false` will disable this feature and the callback will be execute immediately
204 with an error, or an error will be thrown if no callback is specified.
207 var redis = require("redis"),
208 client = redis.createClient(null, null, {detect_buffers: true});
210 client.set("foo_rand000000000000", "OK");
212 // This will return a JavaScript String
213 client.get("foo_rand000000000000", function (err, reply) {
214 console.log(reply.toString()); // Will print `OK`
217 // This will return a Buffer since original key is specified as a Buffer
218 client.get(new Buffer("foo_rand000000000000"), function (err, reply) {
219 console.log(reply.toString()); // Will print `<Buffer 4f 4b>`
224 `createClient()` returns a `RedisClient` object that is named `client` in all of the examples here.
226 ## client.auth(password, callback)
228 When connecting to Redis servers that require authentication, the `AUTH` command must be sent as the
229 first command after connecting. This can be tricky to coordinate with reconnections, the ready check,
230 etc. To make this easier, `client.auth()` stashes `password` and will send it after each connection,
231 including reconnections. `callback` is invoked only once, after the response to the very first
233 NOTE: Your call to `client.auth()` should not be inside the ready handler. If
234 you are doing this wrong, `client` will emit an error that looks
235 something like this `Error: Ready check failed: ERR operation not permitted`.
239 Forcibly close the connection to the Redis server. Note that this does not wait until all replies have been parsed.
240 If you want to exit cleanly, call `client.quit()` to send the `QUIT` command after you have handled all replies.
242 This example closes the connection to the Redis server before the replies have been read. You probably don't
246 var redis = require("redis"),
247 client = redis.createClient();
249 client.set("foo_rand000000000000", "some fantastic value");
250 client.get("foo_rand000000000000", function (err, reply) {
251 console.log(reply.toString());
256 `client.end()` is useful for timeout cases where something is stuck or taking too long and you want
259 ## Friendlier hash commands
261 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.
262 When dealing with hash values, there are a couple of useful exceptions to this.
264 ### client.hgetall(hash)
266 The reply from an HGETALL command will be converted into a JavaScript Object by `node_redis`. That way you can interact
267 with the responses using JavaScript syntax.
271 client.hmset("hosts", "mjr", "1", "another", "23", "home", "1234");
272 client.hgetall("hosts", function (err, obj) {
278 { mjr: '1', another: '23', home: '1234' }
280 ### client.hmset(hash, obj, [callback])
282 Multiple values in a hash can be set by supplying an object:
285 "0123456789": "abcdefghij", // NOTE: the key and value must both be strings
286 "some manner of key": "a type of value"
289 The properties and values of this Object will be set as keys and values in the Redis hash.
291 ### client.hmset(hash, key1, val1, ... keyn, valn, [callback])
293 Multiple values may also be set by supplying a list:
295 client.HMSET(key1, "0123456789", "abcdefghij", "some manner of key", "a type of value");
298 ## Publish / Subscribe
300 Here is a simple example of the API for publish / subscribe. This program opens two
301 client connections, subscribes to a channel on one of them, and publishes to that
302 channel on the other:
305 var redis = require("redis"),
306 client1 = redis.createClient(), client2 = redis.createClient(),
309 client1.on("subscribe", function (channel, count) {
310 client2.publish("a nice channel", "I am sending a message.");
311 client2.publish("a nice channel", "I am sending a second message.");
312 client2.publish("a nice channel", "I am sending my last message.");
315 client1.on("message", function (channel, message) {
316 console.log("client1 channel " + channel + ": " + message);
318 if (msg_count === 3) {
319 client1.unsubscribe();
325 client1.incr("did a thing");
326 client1.subscribe("a nice channel");
329 When a client issues a `SUBSCRIBE` or `PSUBSCRIBE`, that connection is put into "pub/sub" mode.
330 At that point, only commands that modify the subscription set are valid. When the subscription
331 set is empty, the connection is put back into regular mode.
333 If you need to send regular commands to Redis while in pub/sub mode, just open another connection.
337 If a client has subscriptions active, it may emit these events:
339 ### "message" (channel, message)
341 Client will emit `message` for every message received that matches an active subscription.
342 Listeners are passed the channel name as `channel` and the message Buffer as `message`.
344 ### "pmessage" (pattern, channel, message)
346 Client will emit `pmessage` for every message received that matches an active subscription pattern.
347 Listeners are passed the original pattern used with `PSUBSCRIBE` as `pattern`, the sending channel
348 name as `channel`, and the message Buffer as `message`.
350 ### "subscribe" (channel, count)
352 Client will emit `subscribe` in response to a `SUBSCRIBE` command. Listeners are passed the
353 channel name as `channel` and the new count of subscriptions for this client as `count`.
355 ### "psubscribe" (pattern, count)
357 Client will emit `psubscribe` in response to a `PSUBSCRIBE` command. Listeners are passed the
358 original pattern as `pattern`, and the new count of subscriptions for this client as `count`.
360 ### "unsubscribe" (channel, count)
362 Client will emit `unsubscribe` in response to a `UNSUBSCRIBE` command. Listeners are passed the
363 channel name as `channel` and the new count of subscriptions for this client as `count`. When
364 `count` is 0, this client has left pub/sub mode and no more pub/sub events will be emitted.
366 ### "punsubscribe" (pattern, count)
368 Client will emit `punsubscribe` in response to a `PUNSUBSCRIBE` command. Listeners are passed the
369 channel name as `channel` and the new count of subscriptions for this client as `count`. When
370 `count` is 0, this client has left pub/sub mode and no more pub/sub events will be emitted.
372 ## client.multi([commands])
374 `MULTI` commands are queued up until an `EXEC` is issued, and then all commands are run atomically by
375 Redis. The interface in `node_redis` is to return an individual `Multi` object by calling `client.multi()`.
378 var redis = require("./index"),
379 client = redis.createClient(), set_size = 20;
381 client.sadd("bigset", "a member");
382 client.sadd("bigset", "another member");
384 while (set_size > 0) {
385 client.sadd("bigset", "member " + set_size);
389 // multi chain with an individual callback
393 .keys("*", function (err, replies) {
394 // NOTE: code in this callback is NOT atomic
395 // this only happens after the the .exec call finishes.
396 client.mget(replies, redis.print);
399 .exec(function (err, replies) {
400 console.log("MULTI got " + replies.length + " replies");
401 replies.forEach(function (reply, index) {
402 console.log("Reply " + index + ": " + reply.toString());
407 `client.multi()` is a constructor that returns a `Multi` object. `Multi` objects share all of the
408 same command methods as `client` objects do. Commands are queued up inside the `Multi` object
409 until `Multi.exec()` is invoked.
411 You can either chain together `MULTI` commands as in the above example, or you can queue individual
412 commands while still sending regular client command as in this example:
415 var redis = require("redis"),
416 client = redis.createClient(), multi;
418 // start a separate multi command queue
419 multi = client.multi();
420 multi.incr("incr thing", redis.print);
421 multi.incr("incr other thing", redis.print);
424 client.mset("incr thing", 100, "incr other thing", 1, redis.print);
426 // drains multi queue and runs atomically
427 multi.exec(function (err, replies) {
428 console.log(replies); // 101, 2
431 // you can re-run the same transaction if you like
432 multi.exec(function (err, replies) {
433 console.log(replies); // 102, 3
438 In addition to adding commands to the `MULTI` queue individually, you can also pass an array
439 of commands and arguments to the constructor:
442 var redis = require("redis"),
443 client = redis.createClient(), multi;
446 ["mget", "multifoo", "multibar", redis.print],
447 ["incr", "multifoo"],
449 ]).exec(function (err, replies) {
450 console.log(replies);
457 Redis supports the `MONITOR` command, which lets you see all commands received by the Redis server
458 across all client connections, including from other client libraries and other computers.
460 After you send the `MONITOR` command, no other commands are valid on that connection. `node_redis`
461 will emit a `monitor` event for every new monitor message that comes across. The callback for the
462 `monitor` event takes a timestamp from the Redis server and an array of command arguments.
464 Here is a simple example:
467 var client = require("redis").createClient(),
468 util = require("util");
470 client.monitor(function (err, res) {
471 console.log("Entering monitoring mode.");
474 client.on("monitor", function (time, args) {
475 console.log(time + ": " + util.inspect(args));
481 Some other things you might like to know about.
483 ## client.server_info
485 After the ready probe completes, the results from the INFO command are saved in the `client.server_info`
488 The `versions` key contains an array of the elements of the version string for easy comparison.
490 > client.server_info.redis_version
492 > client.server_info.versions
497 A handy callback function for displaying return values when testing. Example:
500 var redis = require("redis"),
501 client = redis.createClient();
503 client.on("connect", function () {
504 client.set("foo_rand000000000000", "some fantastic value", redis.print);
505 client.get("foo_rand000000000000", redis.print);
512 Reply: some fantastic value
514 Note that this program will not exit cleanly because the client is still connected.
518 Boolean to enable debug mode and protocol tracing.
521 var redis = require("redis"),
522 client = redis.createClient();
524 redis.debug_mode = true;
526 client.on("connect", function () {
527 client.set("foo_rand000000000000", "some fantastic value");
533 mjr:~/work/node_redis (master)$ node ~/example.js
544 `send command` is data sent into Redis and `on_data` is data received from Redis.
546 ## client.send_command(command_name, args, callback)
548 Used internally to send commands to Redis. For convenience, nearly all commands that are published on the Redis
549 Wiki have been added to the `client` object. However, if I missed any, or if new commands are introduced before
550 this library is updated, you can use `send_command()` to send arbitrary commands to Redis.
552 All commands are sent as multi-bulk commands. `args` can either be an Array of arguments, or omitted.
556 Boolean tracking the state of the connection to the Redis server.
558 ## client.command_queue.length
560 The number of commands that have been sent to the Redis server but not yet replied to. You can use this to
561 enforce some kind of maximum queue depth for commands while connected.
563 Don't mess with `client.command_queue` though unless you really know what you are doing.
565 ## client.offline_queue.length
567 The number of commands that have been queued up for a future connection. You can use this to enforce
568 some kind of maximum queue depth for pre-connection commands.
570 ## client.retry_delay
572 Current delay in milliseconds before a connection retry will be attempted. This starts at `250`.
574 ## client.retry_backoff
576 Multiplier for future retry timeouts. This should be larger than 1 to add more time between retries.
577 Defaults to 1.7. The default initial connection retry is 250, so the second retry will be 425, followed by 723.5, etc.
579 ### Commands with Optional and Keyword arguments
581 This applies to anything that uses an optional `[WITHSCORES]` or `[LIMIT offset count]` in the [redis.io/commands](http://redis.io/commands) documentation.
585 var args = [ 'myzset', 1, 'one', 2, 'two', 3, 'three', 99, 'ninety-nine' ];
586 client.zadd(args, function (err, response) {
588 console.log('added '+response+' items.');
590 // -Infinity and +Infinity also work
591 var args1 = [ 'myzset', '+inf', '-inf' ];
592 client.zrevrangebyscore(args1, function (err, response) {
594 console.log('example1', response);
595 // write your code here
598 var max = 3, min = 1, offset = 1, count = 2;
599 var args2 = [ 'myzset', max, min, 'WITHSCORES', 'LIMIT', offset, count ];
600 client.zrevrangebyscore(args2, function (err, response) {
602 console.log('example2', response);
603 // write your code here
610 Better tests for auth, disconnect/reconnect, and all combinations thereof.
612 Stream large set/get values into and out of Redis. Otherwise the entire value must be in node's memory.
614 Performance can be better for very large values.
616 I think there are more performance improvements left in there for smaller values, especially for large lists of small values.
619 - open a pull request and then wait for feedback (if
620 [DTrejo](http://github.com/dtrejo) does not get back to you within 2 days,
621 comment again with indignation!)
624 Some people have have added features and fixed bugs in `node_redis` other than me.
626 Ordered by date of first contribution.
627 [Auto-generated](http://github.com/dtrejo/node-authors) on Wed Jul 25 2012 19:14:59 GMT-0700 (PDT).
629 - [Matt Ranney aka `mranney`](https://github.com/mranney)
630 - [Tim-Smart aka `tim-smart`](https://github.com/tim-smart)
631 - [Tj Holowaychuk aka `visionmedia`](https://github.com/visionmedia)
632 - [rick aka `technoweenie`](https://github.com/technoweenie)
633 - [Orion Henry aka `orionz`](https://github.com/orionz)
634 - [Aivo Paas aka `aivopaas`](https://github.com/aivopaas)
635 - [Hank Sims aka `hanksims`](https://github.com/hanksims)
636 - [Paul Carey aka `paulcarey`](https://github.com/paulcarey)
637 - [Pieter Noordhuis aka `pietern`](https://github.com/pietern)
638 - [nithesh aka `nithesh`](https://github.com/nithesh)
639 - [Andy Ray aka `andy2ray`](https://github.com/andy2ray)
640 - [unknown aka `unknowdna`](https://github.com/unknowdna)
641 - [Dave Hoover aka `redsquirrel`](https://github.com/redsquirrel)
642 - [Vladimir Dronnikov aka `dvv`](https://github.com/dvv)
643 - [Umair Siddique aka `umairsiddique`](https://github.com/umairsiddique)
644 - [Louis-Philippe Perron aka `lp`](https://github.com/lp)
645 - [Mark Dawson aka `markdaws`](https://github.com/markdaws)
646 - [Ian Babrou aka `bobrik`](https://github.com/bobrik)
647 - [Felix Geisendörfer aka `felixge`](https://github.com/felixge)
648 - [Jean-Hugues Pinson aka `undefined`](https://github.com/undefined)
649 - [Maksim Lin aka `maks`](https://github.com/maks)
650 - [Owen Smith aka `orls`](https://github.com/orls)
651 - [Zachary Scott aka `zzak`](https://github.com/zzak)
652 - [TEHEK Firefox aka `TEHEK`](https://github.com/TEHEK)
653 - [Isaac Z. Schlueter aka `isaacs`](https://github.com/isaacs)
654 - [David Trejo aka `DTrejo`](https://github.com/DTrejo)
655 - [Brian Noguchi aka `bnoguchi`](https://github.com/bnoguchi)
656 - [Philip Tellis aka `bluesmoon`](https://github.com/bluesmoon)
657 - [Marcus Westin aka `marcuswestin2`](https://github.com/marcuswestin2)
658 - [Jed Schmidt aka `jed`](https://github.com/jed)
659 - [Dave Peticolas aka `jdavisp3`](https://github.com/jdavisp3)
660 - [Trae Robrock aka `trobrock`](https://github.com/trobrock)
661 - [Shankar Karuppiah aka `shankar0306`](https://github.com/shankar0306)
662 - [Ignacio Burgueño aka `ignacio`](https://github.com/ignacio)
666 ## LICENSE - "MIT License"
668 Copyright (c) 2010 Matthew Ranney, http://ranney.com/
670 Permission is hereby granted, free of charge, to any person
671 obtaining a copy of this software and associated documentation
672 files (the "Software"), to deal in the Software without
673 restriction, including without limitation the rights to use,
674 copy, modify, merge, publish, distribute, sublicense, and/or sell
675 copies of the Software, and to permit persons to whom the
676 Software is furnished to do so, subject to the following
679 The above copyright notice and this permission notice shall be
680 included in all copies or substantial portions of the Software.
682 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
683 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
684 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
685 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
686 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
687 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
688 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
689 OTHER DEALINGS IN THE SOFTWARE.
691 ![spacer](http://ranney.com/1px.gif)