Now that you know how to connect with Redis from Node.js, let’s see how to store key-value pairs in Redis storage.

Storing Strings

All the Redis commands are exposed as different functions on the client object. To store a simple string use the following syntax:

client.set('framework', 'AngularJS');

Or

client.set(['framework', 'AngularJS']);

The above snippets store a simple string AngularJS against the key framework. You should note that both the snippets do the same thing. The only difference is that the first one passes a variable number of arguments while the later passes an args array to client.set() function. You can also pass an optional callback to get a notification when the operation is complete:

client.set('framework', 'AngularJS', function(err, reply) {
  console.log(reply);
});

If the operation failed for some reason, the err argument to the callback represents the error. To retrieve the value of the key do the following:

client.get('framework', function(err, reply) {
    console.log(reply);
});

client.get() lets you retrieve a key stored in Redis. The value of the key can be accessed via the callback argument reply. If the key doesn’t exist, the value of reply will be empty.

Storing Hash

Many times storing simple values won’t solve your problem. You will need to store hashes (objects) in Redis. For that you can use hmset() function as following:

client.hmset('frameworks', 'javascript', 'AngularJS', 'css', 'Bootstrap', 'node', 'Express');

client.hgetall('frameworks', function(err, object) {
    console.log(object);
});

The above snippet stores a hash in Redis that maps each technology to its framework. The first argument to hmset() is the name of the key. Subsequent arguments represent key-value pairs. Similarly, hgetall() is used to retrieve the value of the key. If the key is found, the second argument to the callback will contain the value which is an object.

Note that Redis doesn’t support nested objects. All the property values in the object will be coerced into strings before getting stored. You can also use the following syntax to store objects in Redis:

client.hmset('frameworks', {
    'javascript': 'AngularJS',
    'css': 'Bootstrap',
    'node': 'Express'
});

An optional callback can also be passed to know when the operation is completed.

All the functions (commands) can be called with uppercase/lowercase equivalents. For example, client.hmset() and client.HMSET() are the same. Storing Lists

If you want to store a list of items, you can use Redis lists. To store a list use the following syntax: