[Snippet] - Axios download file stream and write file in Node
create:January 10, 2022 update:April 12, 2022 • ☕️ 2 min read
同步链接: 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 国际」许可协议进行许可。 声明:转载请注明出处!