节点.js http 模块未设置'data'侦听器时不关闭连接



考虑以下代码:

const http = require('http')
const req = http.request({hostname: 'www.example.com'}, res=>{
console.log('Response received')
res.on('data',data=>{
console.log('Received: '+data)
})
res.on('end',()=>{
console.log('Connection ended')
})
})
req.end()
如预期的那样,它输出:
Response received
Received data
Connection ended

但是当我删除'data'的事件监听器时,像这样:

const http = require('http')
const req = http.request({hostname: 'www.example.com'}, res=>{
console.log('Response received')
res.on('end',()=>{
console.log('Connection ended')
})
})
req.end()

由于某些原因,它只输出:

Response received

为什么会这样?这是否意味着连接保持打开状态?

还有,为什么设置事件侦听器甚至不影响行为?谢谢你的帮助。

node.js中的流(HTTP响应是)以"pause "模式。他们要么通过呼叫read,要么通过转换成"流"来等待别人阅读。模式下,它们连续发射data事件。将处理程序附加到data事件自动将它们设置为flowing,但由于您从未这样做,因此流只是等待,永远。

您可以调用res.resume()来设置流动模式,而无需为事件附加处理程序。它仍然会读取和发出数据,但是没有侦听该事件,因此数据只是丢失了。

最新更新