NodeJS字符串到缓冲区pdf文件

时间:2018-06-28 17:44:01

标签: node.js

嗨,我正在尝试下载pdf文件并将其保存在我的磁盘上。 API向我发送一个字符串。但是以下代码不起作用。

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

我已经尝试过了,并且正在工作...

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 个答案:

答案 0 :(得分:0)

您需要按以下步骤配置axios获取请求

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.

然后检查响应对象上的结束事件。