【问题标题】:https.get with youtube video returning an empty bufferhttps.get 与 youtube 视频返回一个空缓冲区
【发布时间】:2026-02-06 05:25:01
【问题描述】:

我正在使用 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 视频链接中,所有其他请求都正常工作。

【问题讨论】:

    标签: node.js http download youtube


    【解决方案1】:

    这可能是因为你唱的是on('end'...而不是`on('finish'...)

    因为可能还有其他工作尚未完成。

    【讨论】:

      【解决方案2】:

      发现问题,当请求失败时,是因为 youtube 返回了重定向代码 (302) 而不是直接链接,在重定向导致实际 url 之后,下载没有问题。

      【讨论】: