request-promise download pdf file
Asked Answered
W

3

18

I received multiple pdf files and must download it from a REST-API.

After auth and connect I try to download the file with request-promise:

const optionsStart = {
  uri: url,
  method: 'GET',
  headers: {
      'X-TOKEN': authToken,
      'Content-type': 'applcation/pdf'
    }
  }
  request(optionsStart)
    .then(function(body, data) {
      let writeStream = fs.createWriteStream(uuid+'_obj.pdf');
      console.log(body)
      writeStream.write(body, 'binary');
      writeStream.on('finish', () => {
        console.log('wrote all data to file');
      });
      writeStream.end();
    })

The request create a pdf (approximately 1-2MB) but I can't open it. (Mac Preview show blank pages and adobe show = >

There was an error opening this document. There was a problem reading this document (14).

I have no information about the API Endpoint where I download the files. Just have this curl:

curl -o doc.pdf --header "X-TOKEN: XXXXXX" 
http://XXX.XXX/XXX/docs/doc1

Where is my mistake?

Update:

I opened the file in edit and the file looks like that: file preview

Don't have any experience with that :-)

Wolfenbarger answered 12/2, 2018 at 18:10 Comment(0)
E
23

Add encoding: 'binary' to your request options:

const optionsStart = {
  uri: url,
  method: "GET",
  encoding: "binary", // it also works with encoding: null
  headers: {
    "Content-type": "application/pdf"
  }
};
Entrain answered 12/2, 2018 at 18:45 Comment(5)
If encoding: "binary" doesn't work try encoding: null!Matchlock
@boramalper I had excel sheet (.xlsx), null worked perfectly, thank you a lot!Vaughnvaught
@BoraM.Alper null works perfect with encryption keys on .dat formatGezira
could this answer be fixed to use null, and there is a typo application/pdfMysterious
I had to use null instead of "binary" as well. Under which circumstances would "binary" work anyway? Is there any documentation?Unsightly
K
18

Add encoding: null to your request options:

const optionsStart = {
  uri: url,
  method: "GET",
  encoding: null,
  headers: {
    "Content-type": "application/pdf"
  }
};

Then, turn the response into a Buffer (if necessary):

const buffer = Buffer.from(response);
Kranz answered 20/10, 2018 at 14:58 Comment(1)
If you set encoding: null then you do not need to do Buffer.from(response) since the response will already be a bufferNels
I
2

try this

const optionsStart = {
      uri: url,
      method: 'GET',
      headers: {
          'X-TOKEN': authToken,
          'Content-type': 'application/pdf'
      },
      encoding: null
  }
  request(optionsStart, (err, resp) => {
      let writeStream = fs.createWriteStream(uuid + '_obj.pdf');
      writeStream.write(resp.body, 'binary');
      writeStream.on('finish', () => {
        console.log('wrote all data to file');
      });
      writeStream.end();
  })
Illaffected answered 20/2, 2020 at 19:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.