开发者

How to handle a result from an hgetall() in nodejs (nowjs)?

开发者 https://www.devze.com 2023-03-25 23:22 出处:网络
I am using redis + nowjs. I would like to know how to go about handling a result from an hgetall()? When I try to display the \"result\" in the client side, I only get [object Object] (it is probably

I am using redis + nowjs. I would like to know how to go about handling a result from an hgetall()? When I try to display the "result" in the client side, I only get [object Object] (it is probably a string from the server-side js).

//Redis result is

redis> HSET cards:lightning-bolt name "Lightning Bolt"
(integer) 1
redis> HSET cards:lightning-bolt text "Blah blah blah"
(integer) 1
redis> HGETALL cards:lightning-bolt
1) "name"
2) "Lightning Bolt"
3) "text"
4) "Blah blah blah"
redis>

//In my server js

everyone.now.signalShowRedisCard = function(card_id) {
    var self = this;
    client.hgetall(("cards:%s" % card_id), function (err, res) {
        nowjs.getGroup(self.now.room).now.receiveShowRedisCard(res);
    });
}

//In my client js (the alert just outputs [object Object])

now.receiveShowRedisCard = function(card_data) {
    alert("redis card: "+card_data);
    try {
      console.log('card data: '+ card_data);
    } catch(e) {
      console.log("Firebug not installed.");
  开发者_运维知识库  }
}

Any ideas? Any reply is appreciated.


when using hgetall you get an array of objects back. Depending on the scenario it could be handled like this:

getItems = function(callback){   
    client.hgetall("myhash",function(err, res){
         var items = [];
         for (i in res) {
            items.push(JSON.parse(res[i]));
         }
     callback(items);
     });    
};


From node_redis readme:

client.hgetall(hash)

The reply from an HGETALL command will be converted into a JavaScript Object by node_redis. That way you can interact with the responses using JavaScript syntax.

I don't know how exactly is nowjs handling passing JavaScript objects, but you can try to JSON.stringify the res returned from the hgetall on the server side and then see if you get JSON string on the client. If yes then just parse it back to JavaScript object in order to work with it on the client side.

0

精彩评论

暂无评论...
验证码 换一张
取 消