Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if redis is running -> node js

I just wanted to know, at the beginning of my NodeJS process, if Redis is started or not (so users session will be stored or not).

Here is what I have for the moment :

var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var redis = require("redis");
var client = redis.createClient(global.redis.host, global.redis.port);

// Check if redis is running
var redisIsReady = false;
client.on('error', function(err) {
    redisIsReady = false;
    console.log('redis is not running');
    console.log(err);
});
client.on('ready', function() {
    redisIsReady = true;
    console.log('redis is running');
});

// Here I use express-session, but I want to set a store only if redis is ready
    sessOptions = {
        [...]
    }
    // Store setting
    if (redisIsReady) {
        sessOptions.store = new RedisStore({
            host: global.redis.host,
            port: global.redis.port
        });
    } else {
        console.log("redis is not running - sessions won't be written to disk");
    }
// app.use(session(sessOptions))

Here is what it's output in both cases (when Redis is running or not) :

redis is not running - sessions won't be written to disk
redis is not running
Error: Redis connection to 6379:localhost failed - connect ENOENT

So I have 2 questions :

  1. How can I do to check if redis is running before setting my SessionStore (is there anyway to check synchronously if redis is running) ?

  2. Why does it giving me an error even when redis is running ?

THANKS!


Note : I'm using default host/port (localhost, 6379) and the RedisStore works as expected.

Note 2 : I'm using Windows... but don't be affraid, it should have the same behavior!

Update : Question #2 answered by vmx => Thanks!

Update 2 : Question #1 answered by Nathan => Thanks!

like image 573
Oliboy50 Avatar asked Jun 15 '14 16:06

Oliboy50


People also ask

How do I know if Redis is running?

To start Redis client, open the terminal and type the command redis-cli. This will connect to your local server and now you can run any command. In the above example, we connect to Redis server running on the local machine and execute a command PING, that checks whether the server is running or not.

How do I know if node app is running?

In windows you can simply go to the Task Manager and check for node in the application list. If it is there then it is running in the machine. There is no default page or URL that node server provides from which you can know that node is running on that server by using the Public IP address or domain name.


1 Answers

Example:

 if (client.connected) {
    client.set(key, JSON.stringify(value));
  } else {
    console.log('redis not connected!');
  }
like image 153
suraj gholap Avatar answered Sep 17 '22 04:09

suraj gholap