Node.js下载文件体积翻倍、损坏问题排查求助
问题原因及解决方案
核心原因
- 你错误地将二进制ZIP文件以字符串方式处理:
response返回的chunk是Buffer类型(二进制数据),使用body += chunk时,Node.js会自动把Buffer转成UTF-8字符串,这个过程会破坏二进制数据(比如无法识别的字节被替换、多字节序列被错误解析)。 - 后续用
fs.writeFile写入时,又把被破坏的字符串转回Buffer,最终导致文件体积异常增大且损坏。
修正方案
方案1:收集Buffer后合并(适合中小文件)
直接收集二进制chunk,最后用Buffer.concat合并后写入文件:
const fs = require('fs'); const { https } = require('follow-redirects'); function download(url, callback) { const request = https.get(url, function (response) { const chunks = []; response.on("data", function (chunk) { chunks.push(chunk); }); response.on("end", function () { const body = Buffer.concat(chunks); callback(body); }); request.on("error", function (e) { console.log("Error: " + e.message); }); }); }; const 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"); }) })
方案2:使用管道流(适合大文件,内存占用更低)
直接通过管道将响应流导入文件流,无需手动处理chunk:
const fs = require('fs'); const { https } = require('follow-redirects'); const url = "https://github.com/TheOtherRolesAU/TheOtherRoles/releases/latest/download/TheOtherRoles.zip" const fileStream = fs.createWriteStream("test.zip"); https.get(url, (response) => { response.pipe(fileStream); fileStream.on('finish', () => { fileStream.close(); console.log("Done"); }); }).on('error', (e) => { console.log("Error: " + e.message); fs.unlink("test.zip", () => {}); // 下载失败时清理无效文件 });
内容的提问来源于stack exchange,提问作者sirzento
相关产品推荐
相关产品推荐

