【问题标题】:Nodejs download binary octet-streamNodejs下载二进制八位字节流
【发布时间】:2020-11-04 00:36:42
【问题描述】:

我正在尝试从服务器下载(即在服务器上创建文件的实例)一个 .pdf 文件,该文件以二进制格式返回给我,其中: Content-Type = application / octet-stream.

经过一番网上研究,我来写:

http.get(url.parse(pdfURL), res => {
    let data = [];
    console.log(res.statusCode);
    res.on('data', chunk => {
        data.push(chunk);
    }).on('end', () => {
        let buffer = Buffer.concat(data);
        console.log(buffer.toString('base64'));
        fs.open(path, 'w', (e, fd) => {
            if (e) throw e;
            fs.write(fd, buffer, 0, buffer.length, null, e => {
                if (e) throw e;
                fs.close(fd, () => console.log('Wrote successfully'));
            });
        });
    });
});

一切正常,但是当我尝试打开生成的 pdf 时,它告诉我文件已损坏且不可读。 知道可能出了什么问题吗?

谢谢


编辑: 我注意到邮递员一切正常,所以我认为我对待二进制文件的方式是错误的

【问题讨论】:

    标签: node.js http pdf http-headers mime


    【解决方案1】:

    好的,我明白了, 我没有对响应进行解压缩,现在可以正常工作了

    【讨论】:

      【解决方案2】:

      这对我不起作用,尝试了很多不同的方法,直到我找到 got,一个处理 http 请求的 npm 库,这对我有用:

      const stream = require('stream');
      const { promisify } = require('util');
      const fs = require('fs');
      const got = require('got');
      
      const pipeline = promisify(stream.pipeline);
      
      async function downloadImage(url, name) {
        await pipeline(
          got.stream(url),
          fs.createWriteStream(name)
        );
      }
      

      更多信息在这里:https://bleext.com/post/downloading-images-with-nodejs

      【讨论】:

        猜你喜欢
        • 2020-07-09
        • 1970-01-01
        • 2020-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多