Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
shanejix opened this issue Jan 10, 2022 · 0 comments
Open

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

shanejix opened this issue Jan 10, 2022 · 0 comments

Comments

@shanejix
Copy link
Owner

shanejix commented Jan 10, 2022

同步链接: https://www.shanejix.com/posts/[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");

作者:shanejix
出处:https://www.shanejix.com/posts/[Snippet] - Axios download file stream and write file in Node/
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
声明:转载请注明出处!

@shanejix shanejix changed the title [Snippet] - axios download file stream and write file in node [Snippet] - Axios download file stream and write file in Node Jan 21, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant