node.js axios下载文件流和writeFile

新手上路,请多包涵

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

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

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

如何正确保存文件?

原文由 ar099968 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.8k
2 个回答

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

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

 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() ,并确保下载的文件已完成处理。

或者,如果你使用更现代的 NodeJS 版本,你可以试试这个:

 import * as stream from 'stream';
import { promisify } from 'util';

const finished = promisify(stream.finished);

export async function downloadFile(fileUrl: string, outputLocationPath: string): Promise<any> {
  const writer = createWriteStream(outputLocationPath);
  return Axios({
    method: 'get',
    url: fileUrl,
    responseType: 'stream',
  }).then(response => {
    response.data.pipe(writer);
    return finished(writer); //this is a Promise
  });
}

原文由 csotiriou 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以简单地使用 response.data.pipefs.createWriteStream 将响应传递给文件

axios({
    method: "get",
    url: "https://xxx/my.pdf",
    responseType: "stream"
}).then(function (response) {
    response.data.pipe(fs.createWriteStream("/temp/my.pdf"));
});

原文由 ponury-kostek 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题