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

前端 未结 2 899
长情又很酷
长情又很酷 2021-02-01 08: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 -

相关标签:
2条回答
  • 2021-02-01 08:41

    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());
    
        });
    
    0 讨论(0)
  • 2021-02-01 08:44

    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.

    0 讨论(0)
提交回复
热议问题