1

I have a Node.js code. While running this code, i have an error.

This error is

ClientClosedError: The client is closed

My redis run on docker called redis1.

const redis = require("redis");
const client = redis.createClient({
    host: '127.0.0.1',
    port: 6379
});




client.on("error", error => {
    if(error) {
        console.error("ERROR***",error);
    }else {
        console.log("Redis connect.");
    }
});


//SET
client.set("user_name", "Furkan", (err, msg) => {
    if(err) {
        console.error("Error while connecting redis", err);
    }else {
        console.log(msg);
    } 
})

Furhermore; when i was run this code, dont log in terminal any code. Namely when i was run this code, didnt log in terminal ERROR*** , Redis Connected or Error while connecting redis.

These logs is exists in my code.

this link is reference for me.

How can i fix this code.?

3 Answers 3

4

You should add in your code before the client code or set code,

(async () => {
   client.connect();
})();

block.

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

Comments

0

you have to running redis-server on docker.

docker run -d --name redis-stack-server -p 6379:6379 redis/redis-stack-server:latest

Comments

0
const redis = require("redis");
const client = redis.createClient({
    host: '127.0.0.1',
    port: 6379
});

 client.on("error", error => {
   if(error) {
       console.error("ERROR***",error);
   }else {
       console.log("Redis connect.");
   }
});

client.connect();

//SET
await client.set("user_name", "Furkan", (err, msg) => {
   if(err) {
       console.error("Error while connecting redis", err);
   }else {
       console.log(msg);
   } 
})

const message = await client.get('user_name');
console.log(message);

client.disconnect();

I know this works. But I'm a beginner so I don't know why putting await solves the problem.

But you most definitely have to do client.connect() before client.get or client.set. Because you have to make a connection first.

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.