javascript - Node.js:http 完成事件、响应关闭事件和响应结束事件之间的区别

标签 javascript node.js http events

我是 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 the stream.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.getfinish 事件将在发出请求后立即触发,然后 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.

因此事件按以下顺序触发:finishendclose

关于javascript - Node.js:http 完成事件、响应关闭事件和响应结束事件之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526179/

相关文章:

javascript - 选择选项卡时,显示下一个选项卡。如果选择最后一个选项卡,则显示第一个选项卡( polymer 纸选项卡+滚动 spy )

mysql - 使用express、mysql和node.js的get方法发送变量的最佳方式是什么

Node.js fs.watchFile 持久监视机制?

node.js - webpack 5 错误 "Can' t 解析 'uglify-js' , '@swc/core' , 'esbuild'

http - Angular 2 http delete 不发出网络请求

http - 后续请求的基本 HTTP 身份验证

javascript - ES6 全局符号是否被垃圾收集?

javascript - IE 和 Chrome 中未定义的 JQuery javascript 参数

javascript - 从网络访问 firebase 数据库

python - 如何在 Python 2 中发送 HEAD HTTP 请求?