Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node http res.end

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?

like image 667
hudsond7 Avatar asked Dec 16 '14 16:12

hudsond7


People also ask

What is RES end in node?

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.

What does res end mean?

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.

Does Res end return?

res. send and end are express functions to return data for the client.

Does Res send end the function?

send doesn't return the function, but does close the connection / end the request.


1 Answers

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.

like image 121
Rodrigo Medeiros Avatar answered Sep 29 '22 22:09

Rodrigo Medeiros