How to use Redis with Node.js

Redis is an open source, BSD licensed, advanced key-value cache and store. It is often referred to as a data structure server since keys can contain stringshasheslistssetssorted setsbitmaps and hyperloglogs.

Comparison with Memcache and Memcached can be found here, and the naming distinction can be found here.

You can download the installation zip file here (I used the Windows version), and extract it to C:\redis. To run the Redis server (in order to be able to save to it and query it) you have to execute the redis-server.exe from this directory.

To use Redis with Node.js you have install the redis module:

npm install redis

A simple usage example:

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

// if you'd like to select database 3, instead of 0 (default), call
// client.select(3, function() { /* ... */ });

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();
});

A lot more examples here.

Written by Nikola Brežnjak