skip to Main Content

I am trying to implement redis into my nodejs and expressjs API REST, but for some reason I am getting the error The client is closed.

  1. I´ve installed redis for windows
  2. I´ve ran redis-server in the cmd.
  3. I´ve tested the redis cli by runing redis-cli and then passing ping. PONG was logged as a result, so it is working.

Created a middleware init_redis.js

const redis = require('redis');

const createConnectedClient = async () => {
    
        const client = redis.createClient({
            host: 'localhost',
            port:  6379,
        });

        client.on('error', (err) => {
            console.log('Redis client error', err);
        });

        await client.connect();

        return client;
};

module.exports = createConnectedClient;

I tried to test redis in my server.js

const createConnectedClient = require('./middleware/init_redis');

let redisClient;

(async () => {
    try {
        redisClient = await createConnectedClient();
        redisClient.on('error', (err) => {
            console.log('Redis client error', err);
        });
    } catch (error) {
        console.error('Failed to connect to Redis:', error);
    }
})();

(async () => {
    if (redisClient) {
        try {
            await redisClient.set('foo', 'bar');
            const value = await redisClient.get('foo');
            console.log(value);
        } catch (err) {
            console.error('Error setting or getting key from Redis:', err);
        }
    }
})();

When I run my nodejs server, I get The client is closed. Why is this happening if my redis server is running and I am connectinc my client?

If I do asynchronous functions to run the client, nothing is being logged in my console.

2

Answers


  1. Assuming you are using the latest version of redis in npm ( 4.6.13 ), it is documented that the function createClient in the Redis package is asynchronous, meaning you must wait for the connection to be established for it to work correctly.

    Notice that you call createClient but do not handle the promise nor call await on the function call ( https://www.npmjs.com/package/redis#basic-example ).

    The line requiring the client (const redisClient = require('./middleware/init_redis');) creates the client, then the program attempts to use it immediately after, thus resulting in the error you are getting: The client is closed; you are not allowing the client to successfully establish the connection before using the client.

    Login or Signup to reply.
  2. This should work:

    await redisClient.connect();
    
    await redisClient.set('foo', 'bar', (err, reply) => {
      if (err) throw err;
      console.log(reply);
    });
    
    const value = await redisClient.get('foo', (err, result) => {
      if (err) throw err;
      console.log(result);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search