I'm writing a Node.js application that makes an HTTP request, and then depending on the headers it receives, I want to either process the results of that request, or terminate the request. In particular, if the file I'm attempting to download is too large, I want to stop the request (and the download; that means I can't just ignore the results, because it will still be downloading in the background). Is there a way to do this? I can't find it in the Node docs. Example code:
http.get(requestParams, function(res) {
var bodyData = "";
try {
if(parseInt(res.headers['content-length']) > settings.maxSize) {
done(new Error("Response is too large: " + res.headers['content-length']));
// is there something I should do here to end the request?
return;
} else {
log.debug("Content length of " + res.headers['content-length'] + " is under limit of " + settings.maxSize);
}
} catch(ex) {
done(new Error("Error parsing content-length from response header:" + util.inspect(ex)));
return;
}
res.setEncoding('utf8');
res.on('data', function (chunk) {
bodyData += chunk;
});
res.on('end', function() {
done(null, bodyData);
});
}).on('error', function(e) {
done(e);
});
http.get() returns a request object, which has an abort method, which you can use to abort the current request
E.G.
var req = http.get(params, function(res){
//content-length too large
req.abort();
});
From the docs - http://nodejs.org/api/http.html#http_request_abort
Aborts a request. (New since v0.3.8.)
So unless you are using a very old version of node this should work for you.