我目前正在学习节点,我正在寻找允许我发送GET请求的HTTP库,而无需下载服务器响应内容(正文(。
我需要每分钟发送大量的 http 请求。但是我不需要阅读它们的内容(也是为了节省带宽(。我不能为此目的使用 HEAD。
有没有办法避免使用节点请求或任何其他库下载响应正文?
我使用节点请求的示例代码:
const options = {
url: "https://google.com",
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
}
}
//How to avoid downloading a whole response?
function callback(err, response, body) {
console.log(response.request.uri.host + ' - ' + response.statusCode);
}
request(options, callback);
按标准HTTP GET
获取文件内容,您无法避免下载(获取响应(它,但您可以忽略它。这基本上就是你正在做的事情。
request(options, (err, response, body)=>{
//just return from here don't need to process anything
});
编辑1:若要仅使用响应的几个字节,可以使用 http.get
并使用 data
事件获取数据。从doc
:
http.get('http://nodejs.org/dist/index.json', (res) => {
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
//this is when the response will end
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});