Node http res.end

I am currently reading "Node.js in Action" and also following through a number of online learning resources. One of the first examples in the book shows how to stream through a response. For example:

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 important is this code? I was under the impression that when using http, you should always end up with:

res.end();

      

Isn't that necessary, since the pipeline implies the end? Whenever you write an answer, should I always finish it?

+3


source to share


2 answers


When your readable stream finishes reading (file image.png

), by default it will also end()

fire an event that will trigger an event end()

on the stream being written (stream res

). You don't need to worry about calling end()

in this case.

It should be noted that in this case yours res

will no longer be writable after the event is called end()

. So, if you want to store it for writing, just pass the parameter end: false

to pipe()

, for example:



fs.createReadStream("./image.png").pipe(res, { end: false });

      

and then call the event end()

in the future.

+2


source


end () is not required for streams. There is a large collection of tutorials here . One exercise (# 11 http file server with streams) is to create a static file server. this is what the code looks like:

var fs = require('fs'),
    http = require('http'),
    port = parseInt( process.argv[2] ),
    file = process.argv[3],
    opts = { encoding:'utf8' },
    server;

server = http.createServer(function(req, res) {
    console.log( 'request url: ', req.url );

    res.writeHead(200, { 'Content-type':'text/plain' });
    var stream = fs.createReadStream( file );
    stream.pipe( res );

    stream.on('end', function() {
        console.log('stream ended...');
    });
});


server.listen( port, function() {
    console.log('server listening on port: ', port );
});

      



Lots of other good tutorials and examples. Hope this helps.

0


source







All Articles