I am currently reading through "Node.js in action" as well as following through a number of online learning resources. One of the first examples in the book is showing how to pipe a stream through to a response. Like so:
var http = require('http'),
fs = require('fs');
http.createServer(function(req, res){
res.writeHead(200, {"Content-Type": "image/png"});
fs.createReadStream("./image.png").pipe(res);
}).listen(xxxx)
My question is how valid is this code? I was under the impression that when ever using the http you should always end with:
res.end();
Is this not necessary as piping it implies an end? When ever writing a response should I always end it?
end() Method. Express JSServer Side ProgrammingProgramming. The res. end() method ends the current response process. This method is used to quickly end the response without any data.
res. end() is used to quickly end the response without sending any data. An example for this would be starting a process on a server: app.
res. send and end are express functions to return data for the client.
send doesn't return the function, but does close the connection / end the request.
When your readable stream finishes reading (the image.png
file), by default, it emits and end()
event, which will call the end()
event on the writable stream (the res
stream). You don't need to worry about calling end()
in this case.
It's worth point out that, in this scenario, your res
will no longer be writable after the end()
event is called. So, if you want to keep it writable, just pass the end: false
option to pipe()
, like:
fs.createReadStream("./image.png").pipe(res, { end: false });
, and then call the end()
event sometime in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With