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.
So here are my questions:
- 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.
Sample simplified code:
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.
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.
Express extends Connect which extends HTTP I believe. Looking at the HTTP API, it seems that what you are looking for is
response.write
, which takes a chunk of data to send as a response body. I then believe you can useresponse.end
on the end signal.The
response
object is a writable stream. Just write to it, and Express will even set up chunked encoding for you automatically.You can also pipe to it if whatever is creating this "file" presents itself as a readable stream. http://nodejs.org/api/stream.html
The response object can be written to. In your case, the following would be a solution:
If you have the opportunity to get the file as a stream this can be streamlined further:
Besides using
Response.write()
method to chunk send andResponse.end()
to mark the end!If you have a stream! You can pipe it directly to the Response object! And all get handled automatically!
See the example bellow for a file readable stream:
You can do that with any Stream. Just pipe it to Respond object!
The example above come from here:
https://nodejs.org/en/knowledge/advanced/streams/how-to-use-fs-create-read-stream/
Bottom line
Use pipe! And it's nice too look and understand better!
Here the link from the doc!
https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
And note about chaining
example:
Read the doc for more!
the easy way to do this is to convert the data into a readable stream and pipe it to the response object. here is my nodejs code. hope this might help