通过节点请求模块的图像下载已损坏

时间:2019-06-25 16:08:01

标签: node.js image request filesystems

我正在尝试通过npm request module下载图像,并用fs.writeFile保存,但是,将其保存在磁盘上时,该文件已损坏,并通过imagemagick identify命令进行了验证。

const fs = require('fs');
const path = require('path');
const request = require('request');

const brandLogoUrl  = 'https://example.net/logo.png';
const filename      = path.basename(brandLogoUrl);
const brandLogoPath = `./${filename}`;

request(brandLogoUrl, (error, rsp, body) =>  {
        fs.writeFile(brandLogoPath, body, 'binary', (err) => {
            console.log('brand logo saved');
        });
    });
});

当我用identify检查保存的文件时,结果:

  

识别:图片标题“ logo.png”不正确@   错误/png.c/ReadPNGImage/3940。

但是,如果我通过wget下载相同的URL并用identify进行检查,则结果为

  

logo.png PNG 283x109 283x109 + 0 + 0 8位sRGB 19KB 0.000u 0:00.000

JS看起来很简单,但是似乎有些东西我忽略了。你能发现吗?

编辑

我尝试了https模块(基于this post),并且有效

var fs = require('fs');
var https = require('https');
//Node.js Function to save image from External URL.
var url = 'https://example.net/logo.png';
var file = fs.createWriteStream('./logo.png');
https.get(url, function(response) {
    response.pipe(file);
});

1 个答案:

答案 0 :(得分:1)

您缺少的是响应的编码。使用此库发出请求时,默认情况下,该请求被编码为字符串(utf-8)。根据{{​​3}},您必须传递encoding: null才能正确获取二进制数据。

因此您的代码应如下所示:

request({ url: brandLogoUrl, encoding: null }, (error, rsp, body) =>  {
  fs.writeFile(brandLogoPath, body, 'binary', (err) => {
    console.log('brand logo saved');
  });
});

这也是https模块运行良好的原因-它只传递原始数据而没有任何编码。