You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Node.js下载RAR文件?解决下载后文件为空且无报错问题

解决Node.js下载RAR文件生成空文件的问题

常见原因及修复方案

  • 未处理HTTP重定向:多数文件下载链接会返回3xx重定向状态码,https.get默认不会自动跟进重定向,导致无实际数据写入文件。
  • 未捕获完整错误事件:原代码仅监听了https.get的error事件,但response和createWriteStream实例的error事件也可能触发,未监听则无法发现报错。
  • 未验证响应状态:若服务器返回4xx/5xx错误,响应体可能为空,直接pipe会生成空文件。

修复后的代码

const https = require('https');
const { createWriteStream } = require('fs');

const downloadFile = (url, path) => {
  return new Promise((resolve, reject) => {
    const request = https.get(url, (response) => {
      // 处理重定向
      if (response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
        downloadFile(response.headers.location, path).then(resolve).catch(reject);
        request.destroy();
        return;
      }

      // 验证响应状态
      if (response.statusCode !== 200) {
        reject(new Error(`请求失败,状态码:${response.statusCode}`));
        response.resume(); // 释放响应资源
        return;
      }

      const file = createWriteStream(path);
      
      // 监听文件写入错误
      file.on('error', (err) => {
        file.close();
        reject(err);
      });

      response.pipe(file);

      file.on('finish', () => {
        file.close();
        resolve();
      });
    });

    // 监听请求错误
    request.on('error', (err) => {
      reject(err);
    });
  });
};

额外排查建议

  • 打印response.statusCode和response.headers,确认服务器返回的状态和内容类型是否正确。
  • 手动访问下载URL,确认浏览器能正常下载完整RAR文件,排除源文件本身为空的问题。
  • 检查目标路径的写入权限,确保Node.js进程有权限写入文件。

内容的提问来源于stack exchange,提问作者kaanrkaraman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 16:36:07