11import fetch from "node-fetch" ;
22import * as fs from "fs" ;
33import { strict as assert } from "assert" ;
4+ import { NestedError } from "ts-nested-error" ;
5+
6+ class DownloadFileError extends NestedError { }
47
58/**
69 * Downloads file from `url` and stores it at `destFilePath` with `destFilePermissions`.
@@ -14,13 +17,13 @@ export async function downloadFile(
1417 destFilePermissions : number ,
1518 onProgress : ( readBytes : number , totalBytes : number ) => void
1619) : Promise < void > {
17- const res = await fetch ( url ) ;
20+ const res = await fetch ( url ) . catch ( DownloadFileError . rethrow ( "Failed at initial fetch" ) ) ;
1821
1922 if ( ! res . ok ) {
2023 console . log ( "Error" , res . status , "while downloading file from" , url ) ;
2124 console . dir ( { body : await res . text ( ) , headers : res . headers } , { depth : 3 } ) ;
2225
23- throw new Error ( `Got response ${ res . status } when trying to download a file ` ) ;
26+ throw new DownloadFileError ( `Got response ${ res . status } ` ) ;
2427 }
2528
2629 const totalBytes = Number ( res . headers . get ( 'content-length' ) ) ;
@@ -30,15 +33,21 @@ export async function downloadFile(
3033
3134 console . log ( "Downloading file of" , totalBytes , "bytes size from" , url , "to" , destFilePath ) ;
3235
36+ // Here reject() may be called 2 times. As per ECMAScript standard, 2-d call is ignored
37+ // https://tc39.es/ecma262/#sec-promise-reject-functions
38+
3339 return new Promise < void > ( ( resolve , reject ) => res . body
3440 . on ( "data" , ( chunk : Buffer ) => {
3541 readBytes += chunk . length ;
3642 onProgress ( readBytes , totalBytes ) ;
3743 } )
38- . on ( "error" , reject )
39- . pipe ( fs
40- . createWriteStream ( destFilePath , { mode : destFilePermissions } )
41- . on ( "close" , resolve )
42- )
44+ . on ( "error" , err => reject (
45+ new DownloadFileError ( `Read-stream error, read bytes: ${ readBytes } ` , err )
46+ ) )
47+ . pipe ( fs . createWriteStream ( destFilePath , { mode : destFilePermissions } ) )
48+ . on ( "error" , err => reject (
49+ new DownloadFileError ( `Write-stream error, read bytes: ${ readBytes } ` , err )
50+ ) )
51+ . on ( "close" , resolve )
4352 ) ;
4453}
0 commit comments