问题
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?
回答1:
Maybe you are looking for a way to stream the data
Express
Normally you respond with res.send(data)
, it can be called only once.
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 : 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.
来源:https://stackoverflow.com/questions/45849147/send-data-in-chunks-with-nodejs