繁体   English   中英

下载的文件被保存了两次?

[英]Downloaded file gets saved two times?

我想下载一个 windows 告诉我大小为 76mb 的文件(右键单击属性显示为 74mb)。 但是当我用下面的代码下载它时,文件将是 139mb(属性显示 142mb)大。 文件似乎被保存了两次,导致文件损坏。

const fs = require('fs');
const { http, https } = require('follow-redirects');

function download(url, callback) {
    var request = https.get(url, function (response) {
        var body = "";

        response.on("data", function (chunk) {
            body += chunk;
        });

        response.on("end", function () {
            callback(body);
        });

        request.on("error", function (e) {
            console.log("Error: " + e.message);
        });

    });
};

 let url = "https://github.com/TheOtherRolesAU/TheOtherRoles/releases/latest/download/TheOtherRoles.zip"
download(url, (body) => {
    console.log(body.length)
    fs.writeFile("test.zip", body, err => {
        if (err) console.error(err)
        console.log("Done");
    })
})

知道这是怎么发生的吗? 任何不, download()不会被调用两次。

编辑:我忘了提及,但我是从 github 下载的,在 url 有一个重定向,我正在使用这个 package 作为httpshttps://www.npmjs.com/package/follow-redirects

该库工作正常,它没有被保存两次:你没有正确处理传入的数据:它不是String ,它是Buffer ,所以你需要推送每个块,然后合并它们并将它们传递给 writer:

var body = [];

response.on("data", function (chunk) {
    body.push(chunk);
});

response.on("end", function () {
    callback(Buffer.concat(body));
});

或者您可以简单地 pipe 响应writeStream并用一行代码替换所有代码:

const zip = fs.createWriteStream("test.zip");

//...

response.pipe(zip);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM