首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >node.js axios下载文件流和writeFile

node.js axios下载文件流和writeFile
EN

Stack Overflow用户
提问于 2019-03-27 18:17:16
回答 8查看 69.9K关注 1票数 37

我想下载一个pdf文件axios并保存在磁盘上(服务器端)fs.writeFile,我尝试过:

代码语言:javascript
复制
axios.get('https://xxx/my.pdf', {responseType: 'blob'}).then(response => {
    fs.writeFile('/temp/my.pdf', response.data, (err) => {
        if (err) throw err;
        console.log('The file has been saved!');
    });
});

文件已保存,但内容已损坏...

如何正确保存文件?

EN

Stack Overflow用户

回答已采纳

发布于 2020-04-17 18:30:38

实际上,我认为之前接受的答案有一些缺陷,因为它不能正确处理writestream,所以如果你在Axios给你响应后调用"then()“,你最终会得到一个部分下载的文件。

在下载稍大的文件时,这是一个更合适的解决方案:

代码语言:javascript
复制
export async function downloadFile(fileUrl: string, outputLocationPath: string) {
  const writer = createWriteStream(outputLocationPath);

  return Axios({
    method: 'get',
    url: fileUrl,
    responseType: 'stream',
  }).then(response => {

    //ensure that the user can call `then()` only when the file has
    //been downloaded entirely.

    return new Promise((resolve, reject) => {
      response.data.pipe(writer);
      let error = null;
      writer.on('error', err => {
        error = err;
        writer.close();
        reject(err);
      });
      writer.on('close', () => {
        if (!error) {
          resolve(true);
        }
        //no need to call the reject here, as it will have been called in the
        //'error' stream;
      });
    });
  });
}

这样,您就可以调用downloadFile(),呼叫then()在返回的promise上,并确保下载的文件已完成处理。

或者,如果您使用更新版本的NodeJS,您可以尝试执行以下操作:

代码语言:javascript
复制
import * as stream from 'stream';
import { promisify } from 'util';

const finished = promisify(stream.finished);

export async function downloadFile(fileUrl: string, outputLocationPath: string): Promise {
  const writer = createWriteStream(outputLocationPath);
  return Axios({
    method: 'get',
    url: fileUrl,
    responseType: 'stream',
  }).then(async response => {
    response.data.pipe(writer);
    return finished(writer); //this is a Promise
  });
}
票数 79
EN
查看全部 8 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55374755

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档