CNode

express如何支持http chunked,分段返回数据?

问答
Ssopaco发布于9 年前最后回复9 年前6 回复6932 浏览0 收藏

rt

查看回复

回复 (6)

S
sunkuo#1·9 年前

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

I
i5ting#2·9 年前

他问的是bigpipe,见这个吧 https://github.com/i5ting/nodejs-bigpipe-demo

S
sopaco#3·9 年前

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

S
sopaco#4·9 年前

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

S
sopaco#5·9 年前

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

S
sunkuo#6·9 年前

@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

参与回复
登录后即可参与回复。登录