13

I'm running a simple web app backed by node.js, and I'm trying to use redis to store some key-value pairs. All I do is run "node index.js" on the command line, and here's the first few lines of my index.js:

var app = require('express').createServer();
var io = require('socket.io').listen(app);

var redis = require('redis');
var redis_client = redis.createClient();
redis_client.set("hello", "world");
console.log(redis_client.get("hello"));

However, all I get for redis_client.get("hello") instead of "world" is false. Why is it not returning "world"?

(And I am running the redis-server)

What's weird too is that the example code posted here runs fine, and produces the expected output. Is there something I'm doing incorrectly for simple set and get?

5 Answers 5

16

i could bet get is asynchronous, so you would get the value by callback.

Sign up to request clarification or add additional context in comments.

Comments

8

Here you go! For ES6

redis_client.get("hello", (err, data)=>{
  if(err){
    throw err;
  }
  console.log(data);
});

For ES5

redis_client.get("hello", function(err, data){
  if(err){
    throw err;
  }
  console.log(data);
});

Comments

3

This might help someone who hates using callbacks:

Just promisify it without having to use external library by doing something like:

new Promise((resolve, reject) => {
  redis_client.get("hello", (e, data) => {
    if(e){
      reject(e);
    }
    resolve(data);
  });
});

Comments

1

Nowadays, Redis uses a promises API.

const redis = require("redis"); // 4.0.1
const redisClient = redis.createClient();

(async () => {
  await redisClient.connect();
  await redisClient.set("hello", "world");
  console.log(await redisClient.get("hello")); // => world
  await redisClient.quit();
})();

Comments

0

Had the same issue, solved it by using promisify.

const redis = require('redis');
const util = require('util');
const redisUrl ="redis://127.0.0.1:6379";
const client = redis.createClient(redisUrl);

client.set = util.promisify(client.set)

client.get = util.promisify(client.get);


const setRed =async ()=>{
    await client.set('name','Jo');
    let name = await client.get('name');
//prints the value for name
    console.log(name);
}

setRed();

1 Comment

use this instead client.get('foo_rand000000000000', (error, data) => {return res.status(200).send(data)})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.