3

Hi guys i'm trying to download a pdf file and save it on my disk. The API send me a string. But the following code not working.

axios.get('https://myapi.com/download', config).then((res) => {
  var buff = Buffer.from(res.data, 'binary');
  fs.writeFile('file.pdf', buff, function (err) {
    if (err) throw err;
    console.log('Saved!');
  });
}).catch((e) => {
  console.log(e);
})

I've tried it, and working ...

fs.readFile('./download.pdf','binary', function (err, data) {
  var str = data.toString();
  var buff = Buffer.from(str, 'binary');
  fs.writeFile('novopdf.pdf',buff, () => {
    console.log('ok');
  })
});
2
  • Can you elaborate on exactly what issue you are facing? Commented Jun 28, 2018 at 18:03
  • when i save the pdf from API, it`s save an empty document. Commented Jun 28, 2018 at 18:08

1 Answer 1

2

You need to config axios get request as follows

const response = await Axios({
 method: 'GET',
 url: url,
 responseType: 'stream'
})

response.data.pipe(Fs.createWriteStream(path)) // path is location where you want to write the file.

Then check for end event on the response object.

Sign up to request clarification or add additional context in comments.

2 Comments

If you are satisfied with the answer, please upvote the answer.
Thanks! Worked for PDF files. You can also pass this stream as body in some another HTTP request to send it somewhere else (in my case I had to send this stream to a different web server).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.