Guru on Rails

if you don’t sacrifice for your dream then your dream becomes your sacrifice.
Will Nguyen
How to use NodeJS with Redis
Sun 14 Oct 2018

Redis is a database which stores data in RAM so it's pretty fast. However, if server restarted, we will lose data. We use it in cases that we need the speed, storing the data structure in RAM instead of using the complicated ones in code.

Redis

Install redis in MAC OS is simple.

brew update
brew install redis

Starting redis server.

redis-server

We can interact with redis by redis client (built-in).

redis-cli

Have a look on Redis commands here to play with it.

NodeJS

Installing redis dependency.

npm install redis --save

Let's create a redis.js file in your nodeJS project. Then adding these coding lines for create a new client.

var redis = require('redis');
var client = redis.createClient(6379, 'localhost');

Normally it would be fine. However, redis only supports String type of value (key/value). If we want to use JSON type, let's install redis-jsonify and modify the code like this.

var jsonify = require('redis-jsonify')
var redis = require('redis');
var client = jsonify(redis.createClient(6379, 'localhost'));

Note that the port 6379 and localhost are the default configuration of Redis. I put them as arguments in the code to let you notice about that. We can change it, depending on the Redis's configuration.

Now let's add a key/value to Redis and retrieve it then.

client.set('author', { name:'Will Nguyen', title:'Software Engineer' }, redis.print);
client.get('author', function (error, result) {
    if (error) {
        console.log(error);
        throw error;
    }
    console.log('GET result ->' ,result.name, ' - ', result.title);
});

The result would be like this.

The complete source code.

var jsonify = require('redis-jsonify')
var redis = require('redis');
var client = jsonify(redis.createClient(6379, 'localhost')); // default redis's configuration

// Listening for connection
client.on('connect', function() {
    console.log('Redis client connected');
});

client.on('error', function (err) {
    console.log('Something went wrong ' + err);
});


client.set('author', { name:'Will Nguyen', title:'Software Engineer' }, redis.print);
client.get('author', function (error, result) {
    if (error) {
        console.log(error);
        throw error;
    }
    console.log('GET result ->' ,result.name, ' - ', result.title);
});