Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using redis and node.js issue: why does redis.get return false?

Tags:

node.js

redis

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?

like image 501
neptune Avatar asked Jul 16 '11 09:07

neptune


People also ask

Why we use Redis in node JS?

Redis, an in-memory database that stores data in the server memory, is a popular tool to cache data. You can connect to Redis in Node. js using the node-redis module, which gives you methods to retrieve and store data in Redis.

What is Redis Om?

Redis OM Python is a Redis client that provides high-level abstractions for managing document data in Redis.

What is NPM Redis?

Redis is a super fast and efficient in-memory, key–value cache and store. It's also known as a data structure server, as the keys can contain strings, lists, sets, hashes and other data structures. Redis is best suited to situations that require data to be retrieved and delivered to the client as quickly as possible.


3 Answers

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

Edit:
It's really asynchronous: file.js

like image 157
Tobias P. Avatar answered Sep 22 '22 19:09

Tobias P.


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);
});
like image 36
Danyal Shahid Avatar answered Sep 18 '22 19:09

Danyal Shahid


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);
  });
});
like image 23
millenion Avatar answered Sep 21 '22 19:09

millenion