我使用 ytdl-core 获取 youtube 视频的直接网址(以 https://r1-- 等开头的长网址),并使用 https.get 下载它们。大约 70% 的时间当 res.end 被调用时,它返回一个空缓冲区而不是视频的数据。
这是我目前用来处理 http 请求的代码:
function largeHttpGet(url, callback, progress) {
try{
var _current = 0;
var _buffer = [];
var _req = https.get(url, function (res) {
var _total = parseInt(res.headers['content-length'], 10);
res.on('data', function (chunk) {
_buffer.push(chunk);
_current = parseFloat(_current + chunk.length);
progress(_current / _total * 100);
})
res.on('end', function () {
callback(Buffer.concat(_buffer));
//this returns an empty buffer the majority of the time
})
})
}
catch(error){
console.log("[HTTP]: " + error);
}
}
这就是我用来获取 YouTube 视频信息的方法:
getVidInfo(link, function(info){
back.send("return", {"key": key, "data": info} );
})
此错误仅发生在 youtube 视频链接上,所有其他请求都正常工作。
答案 0 :(得分:0)
答案 1 :(得分:0)
发现问题,当请求失败时,是因为 youtube 返回了重定向代码 (302) 而不是直接链接,按照重定向导致实际 url,下载没有问题。