Node.js - clent.hgetall & client.hmset in Redis

Node.jsServer Side ProgrammingProgramming

Redis commands mostly take the input as a single string or an array of strings as arguments and the replies are sent back as a single string or an array of strings. But, while dealing with the hash values, there are a couple of exceptions.

  • The client.hgetall() function in Node.js – Redis returns an Object keyed by the Hash keys. The strings will be returned either as a string or as a buffer depending upon the setting.

  • The client.hmset() function supplies the Hash arguments to Redis.

Syntax

client.hmset()

client.hmset(hash, key1, val1, ...keyN, valN, [callback])

client.hgetall()

client.hgetall(hash, callback)

Example 1

Create a file with the name "hmset.js" and copy the following code snippet. After creating the file, use the command "node hmset" to run this code as shown in the example below −

// client.hmset Demo Example

// Importing the redis & assert module
const redis = require("redis");
const client = redis.createClient();

client.hmset("hi", "foo", "bar", "hello", "world");

Output

There will be no response because the values are stored in Redis DB.

Example 2

// client.hgetall() Demo Example

// Importing the redis & assert module
const redis = require("redis");
const client = redis.createClient();

client.hmset("hi", "foo", "bar", "hello", "world");

client.hgetall("hi", function(err, value) {
   console.log(value.foo);
   console.log(value.hello);
});

Output

C:\home\node>> node hgetAll.js
bar
world
raja
Updated on 17-Jan-2022 11:47:52

Advertisements