0

Why is the downloaded image malformed?

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));

The resulting image is malformed and can't be opened. Any ideas on what's causing the problem and how to fix it?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Kiril
  • 39,672
  • 31
  • 167
  • 226
  • Possible duplicate of [Getting binary content in Node.js using request](http://stackoverflow.com/questions/14855015/getting-binary-content-in-node-js-using-request) – GilZ Mar 09 '17 at 13:32

1 Answers1

2

By default, request treats the response as utf-8 text. If you want to preserve the response as binary (specifically as a single Buffer), you need to explicitly set encoding: null in your request() options.

mscdex
  • 104,356
  • 15
  • 192
  • 153