Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to end a node.js http request early

I'm requesting a remote file using an https.request in node.js. I'm not interested in receiving the whole file, I just want what's in the first chunk.

var req = https.request(options, function (res) {
    res.setEncoding('utf8');

    res.on('data', function (d) {
         console.log(d);
         res.pause(); // I want this to end instead of pausing
    });
});

I want to stop receiving the response altogether after the first chunk, but I don't see any close or end methods, only pause and resume. My worry using pause is that a reference to this response will be hanging around indefinitely.

Any ideas?

like image 280
Stuart Memo Avatar asked Aug 01 '12 14:08

Stuart Memo


1 Answers

Pop this in a file and run it. You might have to adjust to your local google, if you see a 301 redirect answer from google (which is sent as a single chunk, I believe.)

var http = require('http');

var req = http.get("http://www.google.co.za/", function(res) {
  res.setEncoding();
  res.on('data', function(chunk) {
    console.log(chunk.length);
    res.destroy(); //After one run, uncomment this.
  });
});

To see that res.destroy() really works, uncomment it, and the response object will keep emitting events until it closes itself (at which point node will exit this script).

I also experimented with res.emit('end'); instead of the destroy(), but during one of my test runs, it still fired a few additional chunk callbacks. destroy() seems to be a more imminent "end".

The docs for the destroy method are here: http://nodejs.org/api/stream.html#stream_stream_destroy

But you should start reading here: http://nodejs.org/api/http.html#http_http_clientresponse (which states that the response object implements the readable stream interface.)

like image 138
rdrey Avatar answered Oct 02 '22 06:10

rdrey