为什么下载的图像格式不正确?

时间:2017-02-10 14:44:07

标签: node.js jpeg http-get requestjs

为什么下载的图片格式不正确?

import * as fs from 'fs';
import * as request from 'request-promise-native';

const download = async (url) => {
  console.log(`Downloading ${url}`);
  const options = {
    url,
    resolveWithFullResponse: true,
  };
  const response = await request.get(options);
  console.dir(response.headers);
  return fs.writeFileSync('image.jpg', response.body);
};


const main = async () => {
  try {
    await download('https://dz2cdn1.dzone.com/storage/rc-covers/3339976-refcard-cover141.png');
  } catch (e) {
    console.error(e);
  }
};

main().then(() => console.log('success')).catch((e) => console.log(e));

生成的图像格式不正确,无法打开。关于导致问题的原因以及如何解决问题的任何想法?

1 个答案:

答案 0 :(得分:2)

默认情况下,request将响应视为utf-8文本。如果您希望将响应保留为二进制(特别是单个Buffer),则需要在encoding: null选项中明确设置request()