How do I issue HGET/GET command for Redis Database via Node.js?
Asked Answered
I

3

14

I am using Node.js and a Redis Database . I am new to Redis .

I am using the https://github.com/mranney/node_redis driver for node.

Initialization code -

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

I tried setting up some key value pairs -

client.hset("users:123" ,"name", "Jack");

I wish to know I can get the name parameter from Redis via Node .

I tried

var name = client.hget("users:123", "name");  //returns 'true'

but it just returns 'true' as the output. I want the value ( i.e - Jack ) What is the statement I need to use ?

Isreal answered 14/5, 2012 at 13:41 Comment(0)
S
25

This is how you should do it:

client.hset("users:123", "name", "Jack");
// returns the complete hash
client.hgetall("users:123", function (err, obj) {
   console.dir(obj);
});

// OR

// just returns the name of the hash
client.hget("users:123", "name", function (err, obj) {
   console.dir(obj);
});

Also make sure you understand the concept of callbacks and closures in JavaScript as well as the asynchronous nature of node.js. As you can see, you pass a function (callback or closure) to hget. This function gets called as soon as the redis client has retrieved the result from the server. The first argument will be an error object if an error occurred, otherwise the first argument will be null. The second argument will hold the results.

Sectionalism answered 14/5, 2012 at 14:6 Comment(3)
What is the typo ? I added a semicolon which I had missed .Isreal
Ok. Now I understand why callbacks are necessary for GET,HGET . Thanks !Isreal
you forgot the quotes around "Jack" in the hset command. And second you forgot the quote in the hget command, after user:123Sectionalism
I
0

I found the answer -

A callback function is needed for getting the values .

client.hget("users:123", "name", function (err, reply) {

    console.log(reply.toString());

    });
Isreal answered 14/5, 2012 at 14:3 Comment(3)
Can anyone tell me why do we need to do this kind of callback ?Isreal
This is JavaScript bro ;)Mastitis
Callback is needed as it takes some time to get the results from the DB. Javascript being single threaded - its good to let the control get out of the function and return when the result it available. That way it doesnt block the entire thread. Hence callbacks.Isreal
B
0

If you are using redis version 4.X + ,then no more callback would be needed .All method like get () ,hget() etc. returns a promises.

Beneficence answered 19/2, 2023 at 10:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.