我是 NodeJS 的新手,在查看了文档并尝试了 http.on('finish')
、res.on('close')
之后和 res.on('end')
,我不明白它们有何不同。
http.get(url, res => {
res.setEncoding('utf8'); // returns string object to data event
res.on('data', string => {
const responseObj = responseDataList.find(responseObj => {
return responseObj.url === url;
});
responseObj.data += string;
});
res.on('close', () => {
console.log('[Interruption] connection closed before response was ended.'); // Never fires
})
res.on('error', console.error);
// TODO: find out difference between response.end and response.close and http.finish events
res.on('end', (data, encoding) => {
// Seems to fire at the same time that http.on('finish') fires
current++;
if (counter === current) {
responseDataList.forEach(responseObj => {
console.log(responseObj.data);
})
}
});
})
.on('error', console.error)
.on('finish', () => {
// Seems to fire at the same time that res.on('end') fires
console.log('response sent')
}); // emitted when the response is sent to the OS (not when it is received by the client)
每一个什么时候开火,它们有什么不同?
最佳答案
一旦 http.get
使用 res
对象调用您的回调,它就会返回 http.ClientRequest
. http.ClientRequest
继承自 Stream
.
所以,根据 docs :
The
finish
event is emitted after thestream.end()
method has been called, and all data has been flushed to the underlying system.
在 http.get
的情况下,stream.end()
在发出请求后立即被调用(参见 here )。注意调用 stream.end()
不同于监听 res.on('end')
事件。
因此对于 http.get
,finish
事件将在发出请求后立即触发,然后 res
对象事件将开始触发。
你的 res
对象是一个 HTTP.IncomingMessage
它实现了 Readable Stream
界面
根据 Readable Stream
文档:
The 'end' event is emitted when there is no more data to be consumed from the stream.
所以 end
先触发,然后 close
也适用于可读流
The 'close' event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates that no more events will be emitted, and no further computation will occur.
因此事件按以下顺序触发:finish
、end
、close
关于javascript - Node.js:http 完成事件、响应关闭事件和响应结束事件之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526179/