1
1
import fetch from "node-fetch" ;
2
2
import * as fs from "fs" ;
3
+ import * as stream from "stream" ;
4
+ import * as util from "util" ;
3
5
import { strict as assert } from "assert" ;
4
6
7
+ const pipeline = util . promisify ( stream . pipeline ) ;
8
+
5
9
/**
6
10
* Downloads file from `url` and stores it at `destFilePath`.
7
11
* `onProgress` callback is called on recieveing each chunk of bytes
@@ -18,16 +22,14 @@ export async function downloadFile(
18
22
const totalBytes = Number ( response . headers . get ( 'content-length' ) ) ;
19
23
assert ( ! Number . isNaN ( totalBytes ) , "Sanity check of content-length protocol" ) ;
20
24
25
+ console . log ( "Downloading file of" , totalBytes , "bytes size from" , url , "to" , destFilePath ) ;
26
+
21
27
let readBytes = 0 ;
22
28
23
- console . log ( "Downloading file of" , totalBytes , "bytes size from" , url , "to" , destFilePath ) ;
29
+ response . body . on ( "data" , ( chunk : Buffer ) => {
30
+ readBytes += chunk . length ;
31
+ onProgress ( readBytes , totalBytes ) ;
32
+ } ) ;
24
33
25
- return new Promise < void > ( ( resolve , reject ) => response . body
26
- . on ( "data" , ( chunk : Buffer ) => {
27
- readBytes += chunk . length ;
28
- onProgress ( readBytes , totalBytes ) ;
29
- } )
30
- . on ( "error" , reject )
31
- . pipe ( fs . createWriteStream ( destFilePath ) . on ( "close" , resolve ) )
32
- ) ;
34
+ await pipeline ( response . body , fs . createWriteStream ( destFilePath ) ) ;
33
35
}
0 commit comments