使用Node.js批量发送数据 [英] Send data in chunks with nodejs
问题描述
我对Node.js很陌生,我正在为Angular 4应用程序开发后端.问题在于后端生成响应所需的全部数据的速度相当慢,我希望在可用时随时间发送数据.我正在阅读有关RxJS的信息,但我真的无法弄清楚如何在节点中使用它,您能帮我吗?
I'm quite new to nodejs and I'm working on a backend for an Angular 4 application. The problem is that the backend is quite slow to produce the whole data for the response and I'd like to send data over time as soon as it's available. I was reading about RxJS but I can't really figure out how to use it in node, can you please help me?
推荐答案
也许您正在寻找一种流数据
Maybe you are looking for a way to stream the data
通常您会用res.send(data)
响应,它只能被调用一次.
Normally you respond with res.send(data)
, it can be called only once.
如果您正在读取和发送大文件,则可以流在使用res.write(chunk)
读取文件数据的同时,在文件读取的结束"事件上,调用res.end()
结束响应.
If you are reading and sending a large file, you can stream the file data while being read with res.write(chunk)
and on the 'end' event of the file reading, you call res.end()
to end the response.
EDIT :正如您所说的,您想要的是在块可用时立即进行流式传输,因此您可以在两次写入之间使用res.flush()
命令(仅在res.write(chunk)
之后刷新).
EDIT : As you state, what you want is to stream as soon as the chunk is available, so you can use the res.flush()
command between writes ( just flush after res.write(chunk)
).
您的情况会更快,但总体压缩效率会大大降低.
It would be much faster in your case but the overall compression will be much less efficient.
这篇关于使用Node.js批量发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!