1

I'm using the request.js node module to make a GET request for an image. The body I get back looks like this:

body: 'u0014�����T���8�\u00029�\u001fZ\u0000m(\u0007�\u001d�A\u0014�9E9Oz@E8s��`8d�x�j`�<rq... etc'

How do I read that as a JPEG?

What I'm doing is just forwarding that content as a PUT request to another endpoint. This is working, except that the image data is no readable on the new URL (which is a CouchDB document attachment).

My PUT request looks like this:

request({
    url: newDocUrl + '/' + aName + "?rev=" + resRev,
    method: 'PUT',
    headers: headersAttachment, //{'Content-Type': 'image/jpeg'}
    body: attachment
}, function(e, r, b) {
    console.log('body', b);
});

Questions: How do I read JPEG data from an HTTP res? What format should JPEG data be to forward an image? (i.e. base64, hex, something else?)

Zach Smith
  • 8,458
  • 13
  • 59
  • 133

2 Answers2

0

I found the answer here:

Node.js get image from web and encode with base64

I didn't know that request.js encodes URL responses. By turning it off the image was posted fine.

Community
  • 1
  • 1
Zach Smith
  • 8,458
  • 13
  • 59
  • 133
0

You can use axios and specify the responseType as stream. Then you can pipe the response data to the createWriteStream method of the fs node module.

The request should be handled like this:

axios({
  method: 'get',
  url: '<your API URL here>',
  responseType: 'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('filename.jpg'))
  });

Now the filename.jpg can be opened as a JPEG image.

Axios Documentation here for this

Soumya Dey
  • 3
  • 1
  • 4