事件侦听器何时附加到 Node.js

When do event listeners get attached in Node.js?

本文关键字:Node js 侦听器 何时附 事件      更新时间:2023-09-26

我正在使用node-redis模块连接到redis。
因此,我正在附加一个事件侦听器来处理无法建立 redis 服务器连接的情况。

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

这是在没有侦听器的情况下发生的错误。

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)

现在我的问题是,这个事件侦听器什么时候附加到"客户端"。在附加事件侦听器之前,是否有可能引发连接拒绝错误?

这是可能的,但当您像现在这样并排运行命令时就不行了。此代码将给出您粘贴的相同错误:

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

这不会在代码中发生的原因是,节点线程在线程中运行时不会屈服于事件处理,因此事件处理将在附加错误处理程序后发生。

您可以全局侦听未捕获的错误事件,以捕获在附加之前发生的错误。

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