Home > Net >  Cannot connect to Redis using node js module
Cannot connect to Redis using node js module

Time:11-30

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

CodePudding user response:

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)
  }
})()
  • Related