I am new to Redis Cache in azure. I am trying to check the connection of the client variable before I write data to it. How can I achieve this in Nodejs?

I tried to fetch the client.connected status but when I do negative tests - such as shutdown the redis server, the client.connected variable isn't receiving anything, hence my code doesn't go any further to fetch eh data from my original server, by passing the cache server.

How can I do this in nodejs?

For robust connection checking when using the redis npm package, you should use retry logic, handle the ready event, and ping to gut check if necessary.

Retry

When creating the client, there is automatically a default retry strategy, however you can pass in options object with retry_strategy to customize it like this:

const client = require('redis').createClient({

  retry_strategy: function(options) {
    if (options.error && options.error.code === "ECONNREFUSED") {
      // End reconnecting on a specific error
      return new Error("The server refused the connection");
    }
    if (options.total_retry_time > 1000 * 60 * 60) {
      // End reconnecting after a specific timeout
      return new Error("Retry time exhausted");
    }
    if (options.attempt > 10) {
      // End reconnecting with built in error
      return undefined;
    }

    // reconnect after
    return Math.min(options.attempt * 100, 3000);
  },

});

Ready

After creating a client, you should listen for connection and other events before proceeding like this:

var client = require('redis').createClient();

client.on('connect'     , () => console.log('connect'));
client.on('ready'       , () => console.log('ready'));
client.on('reconnecting', () => console.log('reconnecting'));
client.on('error'       , () => console.log('error'));
client.on('end'         , () => console.log('end'));

Ping

As mentioned in the redis package docs, there is a 1 to 1 mapping of commands between the node client and the official redis commands, so you can do a final smoke test by calling ping like this:

var client = require('redis').createClient();

client.on('ready', () => {
    let response = client.ping()
    console.log(response)
    // do other stuff
});

Further Reading