Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS String to Buffer pdf file

Tags:

node.js

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

1 Answers

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.

like image 159
Saurabh Ghewari Avatar answered Jan 23 '26 12:01

Saurabh Ghewari