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` with `destFilePermissions`.
7
11
* `onProgress` callback is called on recieveing each chunk of bytes
@@ -20,25 +24,28 @@ export async function downloadFile(
20
24
console . log ( "Error" , res . status , "while downloading file from" , url ) ;
21
25
console . dir ( { body : await res . text ( ) , headers : res . headers } , { depth : 3 } ) ;
22
26
23
- throw new Error ( `Got response ${ res . status } when trying to download a file` ) ;
27
+ throw new Error ( `Got response ${ res . status } when trying to download a file. ` ) ;
24
28
}
25
29
26
30
const totalBytes = Number ( res . headers . get ( 'content-length' ) ) ;
27
31
assert ( ! Number . isNaN ( totalBytes ) , "Sanity check of content-length protocol" ) ;
28
32
33
+ console . log ( "Downloading file of" , totalBytes , "bytes size from" , url , "to" , destFilePath ) ;
34
+
29
35
let readBytes = 0 ;
36
+ res . body . on ( "data" , ( chunk : Buffer ) => {
37
+ readBytes += chunk . length ;
38
+ onProgress ( readBytes , totalBytes ) ;
39
+ } ) ;
30
40
31
- console . log ( "Downloading file of" , totalBytes , "bytes size from" , url , "to" , destFilePath ) ;
41
+ const destFileStream = fs . createWriteStream ( destFilePath , { mode : destFilePermissions } ) ;
42
+
43
+ await pipeline ( res . body , destFileStream ) ;
44
+ return new Promise < void > ( resolve => {
45
+ destFileStream . on ( "close" , resolve ) ;
46
+ destFileStream . destroy ( ) ;
32
47
33
- return new Promise < void > ( ( resolve , reject ) => res . body
34
- . on ( "data" , ( chunk : Buffer ) => {
35
- readBytes += chunk . length ;
36
- onProgress ( readBytes , totalBytes ) ;
37
- } )
38
- . on ( "error" , reject )
39
- . pipe ( fs
40
- . createWriteStream ( destFilePath , { mode : destFilePermissions } )
41
- . on ( "close" , resolve )
42
- )
43
- ) ;
48
+ // Details on workaround: https://github.com/rust-analyzer/rust-analyzer/pull/3092#discussion_r378191131
49
+ // Issue at nodejs repo: https://github.com/nodejs/node/issues/31776
50
+ } ) ;
44
51
}
0 commit comments