express如何支持http chunked,分段返回数据?
发布于 7 年前 作者 sopaco 5850 次浏览 来自 问答

rt

6 回复

这个工作是node http 模块做的事情,express里面的response其实是 http.ServerResponse类。 具体的函数应该是 write()。 其实底层调用的是net模块的函数。

@i5ting @sunkuo 两位大神, 其实俺是想用transfer-encoding:chunked,net模块那个明白,但是express中默认自动调用res.end了,怎么在express中使用这个特性呢。

@i5ting 看了你demo明白了,谢谢

@i5ting 你那个express demo写法是不是省略啥了,都不用声明transfer-encoding:chunked和每个chunked的分隔符吗?

@sopaco 我的理解是transfer-encoding:chunked不是express添加的 狼叔(@i5ting )给的例子里,调用的是res.write,实际上是调用的http.ServerResponse.write 。 如果我们想添加Header transfer-encoding:chunked,需要调用的是http.ServerResponse.writeHeader函数,但是根据文档:

If response.write() or response.end() are called before calling this, the implicit/mutable headers will be calculated and call this function. https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers

也就是说狼叔调用了res.write,实际上隐式的调用了res.writeHead,具体的head声明是http模块自己计算的。

你可以跑下狼叔的例子,然后用curl试一下,你会发现狼叔的例子里,已经返回了Transfer-Encoding: chunked的Header,如下图 Screen Shot 2017-04-13 at 6.50.24 PM.png

回到顶部