Supposed I use http.request in Node.js to send an HTTP request to a server, but the only thing I am interested in is the status code - to see whether it worked or not. What I am explicitly NOT interested in is the response stream.
So, basically my code looks something like that:
var req = https.request(options, {
method: 'POST',
path: '/'
}), function (res) {
// Handle res.statusCode
callback(null);
});
req.write('Some data ...');
req.end();
My question now is whether I have to do anything with the res stream: Do I have to read it, close it, ...?
Do I need something such as:
res.end();
or
res.resume();
or anything like that in order to make sure that the stream is closed and garbage collected properly? Anything to watch out for?
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
//You do not have to write this listener if you don't want to
//but NOde will still get all the chunks of data, and attempt to
//call a callback it will find null, and end up discarding every "chunk"
});
res.resume();//Omitting the above(empty ondata listener) and including this line, would exhibit almost identical behavior, res.resume() being very slightly more performant.
//Not there is no res.end(), even in the version that is processing data
//Calling end() is the job of the sender, not the receiver
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
//req.end() signifies the end of the data that you are writing to the
//responding computer.
http://www.infoq.com/news/2013/01/new-streaming-api-node
See the link above for information as a reference as to why this is now necessary.