45

I am developing an application where chats has to cached and monitored, currently it is an local application where i have installed redis and redis-cli. The problem i'm facing is (node:5368) UnhandledPromiseRejectionWarning: Error: The client is closed Attaching code snippet below

//redis setup
const redis = require('redis');
const client = redis.createClient()//kept blank so that default options are available
  

//runs when client connects
io.on("connect", function (socket) {

  //this is client side socket
  //console.log("a new user connected...");

  socket.on("join", function ({ name, room }, callback) {
    //console.log(name, room);
    const { msg, user } = addUser({ id: socket.id, name, room });
   // console.log(user);
    if (msg) return callback(msg); //accessible in frontend

    //emit to all users
    socket.emit("message", {
      user: "Admin",
      text: `Welcome to the room ${user.name}`,
    });
    //emit to all users except current one
  
    socket.broadcast
      .to(user.room)
      .emit("message", { user: "Admin", text: `${user.name} has joined` });

    socket.join(user.room); //pass the room that user wants to join

    //get all users in the room
    io.to(user.room).emit("roomData", {
      room: user.room,
      users: getUsersInRoom(user.room),
    });

    callback();
  }); //end of join

  //user generated messages
  socket.on("sendMessage",  async(message, callback)=>{
    const user = getUser(socket.id);

    //this is where we can store the messages in redis
    await client.set("messages",message);

    io.to(user.room).emit("message", { user: user.name, text: message });
    console.log(client.get('messages'));
    callback();
  }); //end of sendMessage

  //when user disconnects
  socket.on("disconnect", function () {
    const user = removeUser(socket.id);
    if (user) {
     
      console.log(client)

      io.to(user.room).emit("message", {
        user: "Admin",
        text: `${user.name} has left `,
      });
    }
  }); //end of disconnect

I am getting above error when user sends a message to the room or when socket.on("sendMessage") is called.

Where am I going wrong?

Thank you in advance.

9 Answers 9

93

You should await client.connect() before using the client

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer @Leibale Eidelman :)
51

In node-redis V4, the client does not automatically connect to the server, you need to run .connect() before any command, or you will receive error ClientClosedError: The client is closed.

To solve the issue, do the following:-

import { createClient } from 'redis';

const client = createClient();

await client.connect();

Or you can use legacy mode to preserve the backwards compatibility

const client = createClient({
    legacyMode: true
});

3 Comments

you are calling await outside of an async function
you can wrap in async method like (async () => { await client.connect(); })();
really helped me
7

I was having a similar problem and was able to change the connect code as follows.

const client = redis.createClient({
  legacyMode: true,
  PORT: 5001
})
client.connect().catch(console.error)

Comments

6

client.connect() returns a promise. You gotta use .then() because you cannot call await outside of a function.

const client = createClient();  
client.connect().then(() => {
  ...
})

1 Comment

Your answer could be improved by adding more information on what the code does and how it helps the OP.
3

You cannot call await outside of a function.

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

client
  .connect()
  .then(async (res) => {
    console.log('connected');
    // Write your own code here

    // Example
    const value = await client.lRange('data', 0, -1);
    console.log(value.length);
    console.log(value);
    client.quit();
  })
  .catch((err) => {
    console.log('err happened' + err);
  });

Comments

3

you cannot call await outside of a function. This is what i did that worked me.

const redis = require('redis');

const redisClient = redis.createClient()

redisClient.on('connect', () => {
    console.log('Connected to Redis12345');
})

redisClient.on('error', (err) => {
    console.log(err.message);
})

redisClient.on('ready', () => {
    console.log('Redis is ready');
})

redisClient.on('end', () => {
    console.log('Redis connection ended');
})

process.on('SIGINT', () => {
    redisClient.quit();
})

redisClient.connect().then(() => {
    console.log('Connected to Redis');
}).catch((err) => {
    console.log(err.message);
})

In app.js

//just for testing

const redisClient = require('./init_redis')

redisClient.SET('elon', 'musk', redisClient.print)

My data in redis

Comments

2

use "redis": "3.1.2", version.

3 Comments

Why? Please explain.
using 3.1.2 version fixed my issue . I am using redis 3.2.12 Cant i use redis latest npm package with this version ? @mesutpiskin
1

It may happen that another instance is using the port and hence it won't allow us to use the same port. You can try the new port or you can check using

netstat -ano | find "6379"

this will return PID

if there is a process on that port you can kill it using

taskkill /F /PID <pid>

Then restart the process of connecting.

Comments

1

My setup for redis v4.6.13 package

const { createClient } = require('redis');
const { config } = require('../../config');
const redisConfig = config.redis;

exports.redisClientInit = async () => {
   const client = await createClient({
      socket: {
        host: redisConfig.host,
        rejectUnauthorized: true
      },
      username: redisConfig.user,
      password: redisConfig.password
   });

  await client.connect();

  return client;
};

And I use it like that

const redis = await redisClientInit();

redis.set('new test 3', 'abc');

Result

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.