在node.js express中按部分发送数据 [英] Send data by parts in node.js express
问题描述
我在网上和文档中搜索node.js
express
模块,看来没有办法按部就班地发送数据.我的文件渲染速度不是很快,我想在渲染所有文件之前先发送其中的一部分.
I was searching the web and documentation for node.js
express
module and it seems there is no way to send data by parts. I have a file rendered not very fast and I want to send parts of it before everything is rendered.
这是我的问题:
-
response
上是否有一种方法可以按部分发送数据? -
response.end()
是什么? - 如果无法按部就班地发送数据-背后的原理是什么?我要说的是,如果是这样的话,它看起来比不阻止更具阻塞性.如果较早提供数据,浏览器可以更快地加载信息.
- Is there a method on
response
to send data by parts? - What does
response.end()
? - If there is no way to send data by parts - what is the rationale behind? I would say it looks more blocking than non-blocking if that's true. Browser can load information faster if data is given earlier.
示例简化代码:
app.get(..) {
renderFile(file, function(data) {
response.send(data);
});
response.end();
)
这段代码仅发送第一个数据块.我检查了-正确给出了数据 ,并且多次调用了回调函数.
This piece of code sends only the first chunk of data. I checked - data is given correctly and callback is called more than one time.
我当然可以将数据附加到一个变量中,然后编写response.send(data);
,但是我不喜欢这种方法-这不是它应该起作用的方式.
Of course I can append data to the one variable and then write response.send(data);
but I don't like this approach - it is not the way it should work.
推荐答案
response
对象是可写流.只需对其进行写入,Express甚至会自动为您设置分块编码.
The response
object is a writable stream. Just write to it, and Express will even set up chunked encoding for you automatically.
response.write(chunk);
如果正在创建此文件"的任何内容将其自身呈现为可读流,您也可以通过管道进行传输. http://nodejs.org/api/stream.html
You can also pipe to it if whatever is creating this "file" presents itself as a readable stream. http://nodejs.org/api/stream.html
这篇关于在node.js express中按部分发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!