When do event listeners join Node.js?

I am using the node -redis module to connect to redis.
So, I hook up an event listener to handle the case when the redis server connection cannot be established.

client = redis.createClient(6379, 'localhost')
client.on('error',(err)=>{
    console.log('redis connection refused')
})

This is an error that occurs without a listener.

events.js:141
  throw er; // Unhandled 'error' event
  ^
Error: Redis connection to localhost:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
at Object.exports._errnoException (util.js:837:11)
at exports._exceptionWithHostPort (util.js:860:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1060:14)

Now my question is when this event listener joins the "client". Is it possible that the connection refused an error before the event listener is attached?

+4
source share
1 answer

This is possible, but not when you run commands next to each other, just like you do. This code will give the same error that you inserted:

client = redis.createClient(6379, 'localhost')
setTimeout(function() {
    client.on('error',(err)=>{
        console.log('redis connection refused')
    })
}, 3000);

, , , node , , .

, , , .

process.on('uncaughtException', (err) => {
  console.log('whoops! there was an error');
});
+2

Source: https://habr.com/ru/post/1629364/


All Articles