koen
koen

Reputation: 1057

Can't set keys in Redis in Node.js

I am trying to use Redis in Node.js. I am doing something wrong... I can't get my head around it.

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

client.on("error", function (err) {
    console.log("error event - " + client.host + ":" + client.port + " - " + err);
});

/* first attempt */
console.log('first attempt');

var before = client.get("test");
console.log(before);

if(client.exists("test")) { 
    console.log("The value exists");
} else {
    console.log("The value doesn't exists");
    client.set("test","koen");
}

var after = client.get("test");
console.log(after);

/* second attempt */
console.log('--------------');
console.log('second attempt');

var before = client.get("test");
console.log(before);

if(client.exists("test")) { 
    console.log("The value exists");
} else {
    console.log("The value doesn't exists");
    client.set("test","koen");
}

var after = client.get("test");
console.log(after);

I am unable to set any keys... The following is displayed in the console:

first attempt
false
The value doesn't exists
false
--------------
second attempt
false
The value doesn't exists
false

Upvotes: 0

Views: 2968

Answers (2)

bekite
bekite

Reputation: 3444

Here is an example how to set and get "test":

client.set("test", "koen", function (err, res) {
  console.log("set: ", res)

  client.get("test", function (err, res) {
    console.log("get: ", res);
  });

});

Remember that all your calls must be asynchronous.

Upvotes: 1

Nitzan Shaked
Nitzan Shaked

Reputation: 13598

client.set() is not synchronous. You need to supply a callback as the last argument, at which point your key will have been set.

Upvotes: 1

Related Questions