1. 程式人生 > 其它 >[Snippet] - axios download file stream and write file in node

[Snippet] - axios download file stream and write file in node

同步連結: https://www.shanejix.com/posts/[Snippet] - axios download file stream and write file in node/

step 1:

import fs from "fs-extra";
import axios from "axios";

export async function downloadFile(
  url: string,
  output: string,
  options?: {}
): Promise<string> {
  return new Promise((resolve, reject) => {
    axios({
      headers: {},
      url: url,
      method: "GET",
      responseType: "stream",
    })
      .then((response) => {
        // simply use response.data.pipe and fs.createWriteStream to pipe response to file
        response.data.pipe(fs.createWriteStream(output));
        resolve(output);

        // fix bug:  file may be has been downloaded entirely
      })
      .catch((error) => {
        reject(error);
      });
  });
}

step2:

import fs from 'fs-extra';
import axios from 'axios';

export async function downloadFile(url: string, output: string, options?: {}): Promise<string> {
  // create stream writer
  const writer = fs.createWriteStream(output);

  return axios({
    headers: {},
    url: url,
    method: 'GET',
    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(output);
        }
      });
    });
  });

step3:

import * as stream from "stream";
import { promisify } from "util";
import axios from "axios";

const finished = promisify(stream.finished);

export async function downloadFile(url: string, output: string): Promise<any> {
  const writer = createWriteStream(outputLocationPath);

  return axios({
    method: "get",
    url: url,
    responseType: "stream",
  }).then(async (response) => {
    response.data.pipe(writer);

    //this is a Promise
    return finished(writer);
  });
}

usage:

const output = await downloadFile(fileUrl, "./xx.xx");

作者:shanejix
出處:https://www.shanejix.com/posts/[Snippet] - axios download file stream and write file in node/
版權:本作品採用「署名-非商業性使用-相同方式共享 4.0 國際」許可協議進行許可。
宣告:轉載請註明出處!