4

I have redis up and running on port 6379, connecting via telnet works fine.

I'm trying to connect to it on node.js, but i'm getting no response from the event listeners. If i make a call any function like client.set() I get: "ClientClosedError: The client is closed".

This is the code im running:

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

client.on('connect', () => {
    console.log('connected');
});
client.on('end', () => {
    console.log('disconnected');
});
client.on('reconnecting', () => {
    console.log('reconnecting');
});
client.on('error', (err) => {
    console.log('error', { err });
});

setTimeout(() => {console.log("goodbye") }, 20*1000 );

Nothing happens for 20 seconds, and then it closes

1 Answer 1

8

Starting from v4 of node-redis library, you need to call client.connect() after initializing a client. See this migration guide.

const redis = require('redis');
const client = redis.createClient({ socket: { port: 6379 } });

client.connect();

client.on('connect', () => {
    console.log('connected');
});

You might also want to consider running the client connect method with await in an asynchronous function. So you don't have to worry about event listeners.

const redis = require('redis');

(async () => {
  try {
    const client = redis.createClient({ socket: { port: 6379 } });
    await client.connect();
    console.log('connected');
  } catch (err) {
    console.error(err)
  }
})()
Sign up to request clarification or add additional context in comments.

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.