Nic*_*net 5 post http http-post node.js
我想设置简化的HTTP request()客户端包来中止太大的HTTP资源下载.
让我们假设request()设置为下载URL,资源大小为5千兆字节.我想请求()在10MB后停止下载.通常,当请求得到答案时,它会获取所有HTTP头和后面的所有内容.操作数据后,您已经拥有了所有下载的数据.
在axios中,有一个名为maxContentLength的参数,但我找不到任何类似于request()的参数.
我还必须提一下,我不是为了捕获错误而只是至少下载标题和资源的开头.
const request = require('request');
const URL = 'http://de.releases.ubuntu.com/xenial/ubuntu-16.04.3-desktop-amd64.iso';
const MAX_SIZE = 10 * 1024 * 1024 // 10MB , maximum size to download
let total_bytes_read = 0;
Run Code Online (Sandbox Code Playgroud)
1 - 如果服务器的响应是 gzip 压缩的,您应该启用 gzip 选项。 https://github.com/request/request#examples 为了向后兼容,默认情况下不支持响应压缩。要接受 gzip 压缩的响应,请将 gzip 选项设置为 true。
request
.get({
uri: URL,
gzip: true
})
.on('error', function (error) {
//TODO: error handling
console.error('ERROR::', error);
})
.on('data', function (data) {
// decompressed data
console.log('Decompressed chunck Recived:' + data.length, ': Total downloaded:', total_bytes_read)
total_bytes_read += data.length;
if (total_bytes_read >= MAX_SIZE) {
//TODO: handle exceeds max size event
console.error("Request exceeds max size.");
throw new Error('Request exceeds max size'); //stop
}
})
.on('response', function (response) {
response.on('data', function (chunk) {
//compressed data
console.log('Compressed chunck Recived:' + chunk.length, ': Total downloaded:', total_bytes_read)
});
})
.on('end', function () {
console.log('Request completed! Total size downloaded:', total_bytes_read)
});
Run Code Online (Sandbox Code Playgroud)
注意: 如果服务器不压缩响应,但您仍然使用 gzip 选项/解压缩,则解压缩块和原始块将相等。因此,您可以以任何一种方式进行限制检查(从解压缩/压缩块)但是,如果响应被压缩,您应该检查解压缩块的大小限制
2 - 如果响应未压缩,则不需要 gzip 选项来解压缩
request
.get(URL)
.on('error', function (error) {
//TODO: error handling
console.error('ERROR::', error);
})
.on('response', function (response) {
response.on('data', function (chunk) {
//compressed data
console.log('Recived chunck:' + chunk.length, ': Total downloaded:', total_bytes_read)
total_bytes_read += chunk.length;
if (total_bytes_read >= MAX_SIZE) {
//TODO: handle exceeds max size event
console.error("Request as it exceds max size:")
throw new Error('Request as it exceds max size');
}
console.log("...");
});
})
.on('end', function () {
console.log('Request completed! Total size downloaded:', total_bytes_read)
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2837 次 |
| 最近记录: |