2

I'm trying to save an image using node's file-system that I got from https://picsum.photos/ but the file that is getting written is not what I'm expecting it to be.

const axios = require('axios');
const path = require('path');
const fs = require('file-system');

axios.get('https://picsum.photos/id/237/200/300')
  .then((data) => {
    fs.writeFile(path.resolve(__dirname, '../assets/test/test1.jpg'), data.data, (err) => {
      if (err) {
        console.log(err);
        throw err;
      }
      console.log('file save successfully');
    });
  })
  .catch((err) => {
    console.log(err);
  });

This is what the file results as

tomerpacific
  • 4,704
  • 13
  • 34
  • 52
VinnieGee
  • 21
  • 1
  • 2

1 Answers1

4

The data is probably being returned with the wrong encoding, as none is specified - most likely as text instead of as a binary stream, as the responseType is 'json' by default. There is an example of writing an image to disk with an axios request on the docs, in which responseType is set to stream and the given stream is piped to a writeStream. This is probably the kind of approach you'll need.

Below is the code example given on the docs:

// GET request for remote image
axios({
  method: 'get',
  url: 'https://picsum.photos/id/237/200/300',
  responseType: 'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });

If you want to use writeFile still, you can set responseType: 'arraybuffer' instead, and pass the given buffer to fs.writeFile.

Klaycon
  • 10,599
  • 18
  • 35