Check if redis is running -> node js

2 issues, first the call to create Redis client is in wrong order, the createClient() takes port first, then the host, there's another optional options argument.

var client = redis.createClient(global.redis.port, global.redis.host);

Secondly, you will still not be able to achieve what you are trying to;

  1. The ready event is triggered asynchronously, it may not have received the ready response by the time you check for the redisIsReady flag.
  2. The flag redisIsReady will be set to true, but by now your session initialization code would have probably already executed.

You will have to wait before you get an error or ready event from redis before you initialize your session object.

Hope this helps.


Example:

 if (client.connected) {
    client.set(key, JSON.stringify(value));
  } else {
    console.log('redis not connected!');
  }

How I have done this in the past is in between setting up the redis connection via

var client = redis.createClient(global.redis.port, global.redis.host);

and actually starting my application, whether that be express or a custom app, I just do a very simple query, such as:

client.get(this.testKey, function(err,res) {
  if(err) 
    throw err;

  if(res === expectedValue)
    return startApp();
});

Essentially just put the code to start your app inside of the callback to a redis query, and you will then know if redis is running based on the result.


You can also check using node redis api:

if (client.connected){
  ...
} else {
  ...
}