You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
importfsfrom"fs-extra";importaxiosfrom"axios";exportasyncfunctiondownloadFile(url: string,output: string,options?: {}): Promise<string>{returnnewPromise((resolve,reject)=>{axios({headers: {},url: url,method: "GET",responseType: "stream",}).then((response)=>{// simply use response.data.pipe and fs.createWriteStream to pipe response to fileresponse.data.pipe(fs.createWriteStream(output));resolve(output);// fix bug: file may be not has been downloaded entirely}).catch((error)=>{reject(error);});});}
enhance:
importfsfrom'fs-extra';importaxiosfrom'axios';exportasyncfunctiondownloadFile(url: string,output: string,options?: {}): Promise<string>{// create stream writerconstwriter=fs.createWriteStream(output);returnaxios({headers: {},url: url,method: 'GET',responseType: 'stream',}).then((response)=>{// ensure that the user can call `then()` only when the file has been downloaded entirely.returnnewPromise((resolve,reject)=>{response.data.pipe(writer);leterror=null;writer.on('error',(err)=>{error=err;writer.close();reject(err);});writer.on('close',()=>{if(!error){resolve(output);}});});});
enhance:
import*asstreamfrom"stream";import{promisify}from"util";importaxiosfrom"axios";constfinished=promisify(stream.finished);exportasyncfunctiondownloadFile(url: string,output: string,options?: {}): Promise<string>{// creat stream writerconstwriter=createWriteStream(outputLocationPath);returnaxios({method: "get",url: url,responseType: "stream",}).then(async(response)=>{response.data.pipe(writer);// return a Promisereturnfinished(writer);});}
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
enhance:
enhance:
usage:
The text was updated successfully, but these errors were encountered: