4

I want to write a ueberDB Redis-Handler for my Etherpad.

I absolutely do not understand my problem because with PHP I can set and get key/values without any problems. It only does not work with NodeJS.

Here is a example code:

var redis = require("redis");
client = redis.createClient();
client.on("error", function (err) {
  console.log("Error " + err);
});

client.set("test", "string val", redis.print);
console.log(client.get("test"));

What do I wrong? Maybe somebody has a tip for me.

Treffynnon
  • 21,365
  • 6
  • 65
  • 98
user1078442
  • 43
  • 1
  • 1
  • 3

2 Answers2

8

First, you need to know if your redis client is connected. You can check with console.log(client) and you will see a varaible called "connected". You should see "true"

If you want to use redis in node you should use something like this

    client.set("test","val", function(err) {
        if (err) {
           // Something went wrong
           console.error("error");
        } else {
            client.get("test", function(err, value) {
                 if (err) {
                     console.error("error");
                 } else {
                     console.log("Worked: " + value);
                 }
            });
        }
    });

Keep in mind that all redis function are asynchronous.

malletjo
  • 1,766
  • 16
  • 18
  • Well, be sure you're connected to redis and you can check the content of redis with the command "redis-cli" from CLI – malletjo Dec 03 '11 at 01:00
  • redis 127.0.0.1:6379> set test test OK redis 127.0.0.1:6379> get test "test" redis 127.0.0.1:6379> exit [root@123 tmp]# node 1.js [root@123 tmp]# – user1078442 Dec 03 '11 at 01:02
  • Feel free to accept this answer. Since you're new: read the faq (http://stackoverflow.com/faq) – malletjo Dec 03 '11 at 01:24
2

If it's not obvious from the accepted answer, the reason the posted code is failing is due to the asynchronicity.

You're calling get() before set() has completed.

Benjamin Wootton
  • 2,089
  • 20
  • 21
  • hi Sir, what are the js or nodejs way of working around this asynchronicity that you mentioned. Seems, like the JS's event-driven way of doing things is getting in the way here... – daparic Jun 09 '16 at 21:27