我正在编写一个发出 HTTP 请求的 Node.js 应用程序,然后根据它接收到的标头,我想要么处理该请求的结果,要么终止该请求。特别是,如果我尝试下载的文件太大,我想停止请求(和下载;这意味着我不能忽略结果,因为它仍然会在后台下载)。有没有办法做到这一点?我在 Node 文档中找不到它。示例代码:
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);
});