node logoHello everyone! This is the ninth post in my new node.js modules you should know about article series.

The first post was about dnode - the freestyle rpc library for node, the second was about optimist - the lightweight options parser for node, the third was about lazy - lazy lists for node, the fourth was about request - the swiss army knife of HTTP streaming, the fifth was about hashish - hash combinators library, the sixth was about read - easy reading from stdin, the seventh was about ntwitter - twitter api for node, the eighth was about socket.io that makes websockets and realtime possible in all browsers.

Today I'm going to introduce you to node_redis - the best node.js Redis client API library. Redis node.js module is written by Matt Ranney.

This library is a complete Redis client for node.js. It supports all Redis commands, including many recently added commands like EVAL from experimental Redis server branches.

Here is an example of using redis library:

var redis = require("redis");
var client = redis.createClient();

client.on("error", function (err) {
    console.log("Error " + err);
});

client.set("string key", "string val", redis.print);
client.hset("hash key", "hashtest 1", "some value", redis.print);
client.hset(["hash key", "hashtest 2", "some other value"], redis.print);
client.hkeys("hash key", function (err, replies) {
    console.log(replies.length + " replies:");
    replies.forEach(function (reply, i) {
        console.log("    " + i + ": " + reply);
    });
    client.quit();
});

Here is the output when you run this example:

mjr:~/work/node_redis (master)$ node example.js
Reply: OK
Reply: 0
Reply: 0
2 replies:
    0: hashtest 1
    1: hashtest 2
mjr:~/work/node_redis (master)$ 

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.

Here is an example of passing an array of arguments and a callback:

client.mset(["key 1", "val 1"], function (err, res) {});

Here is that same call in the second style:

client.mset("key 1", "val 1", function (err, res) {});

Note that in either form the callback is optional:

client.set("some key", "some val");
client.set(["some other key", "some val"]);

For a list of Redis commands, see Redis Command Reference.

The commands can be specified in uppercase or lowercase for convenience - client.get() is the same as client.GET().

You can install redis through npm as always:

npm install redis

Redis on GitHub: https://github.com/mranney/node_redis.

Pieter Noordhuis has written a binding to the official hiredis C library, which is non-blocking and fast. It's called hiredis-node. To use hiredis, do:

npm install hiredis redis

If hiredis is installed, node_redis will use it by default. Otherwise, a pure JavaScript parser will be used.