Loading

[Snippet] - Axios download file stream and write file in Node

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 not has been downloaded entirely
      })
      .catch((error) => {
        reject(error);
      });
  });
}

enhance:

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

    });
  });

enhance:

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,
  options?: {}
): Promise<string> {
  // creat stream writer
  const writer = createWriteStream(outputLocationPath);

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

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

usage:

const output = await downloadFile(fileUrl, "./xx.xx");
posted @ 2022-01-10 17:54  shanejix  阅读(93)  评论(0)    收藏  举报