@@ -23,7 +23,6 @@ import * as os from 'os';
23
23
import * as path from 'path' ;
24
24
// @ts -ignore
25
25
import * as tmp from 'tmp' ;
26
- import { Readable } from "stream" ;
27
26
28
27
export abstract class Emulator {
29
28
binaryPath : string | null = null ;
@@ -58,33 +57,47 @@ export abstract class Emulator {
58
57
const filepath : string = path . resolve ( dir , this . binaryName ) ;
59
58
const writer = fs . createWriteStream ( filepath ) ;
60
59
console . log ( `Downloading emulator from [${ this . binaryUrl } ] ...` ) ;
61
- const downloadPromise = new Promise ( ( downloadComplete , downloadFailed ) => {
62
- try {
63
- fetch ( this . binaryUrl ) . then ( resp => {
64
- const reader = resp . body ?. getReader ( ) ;
65
- reader ?. read ( ) . then ( function readStuff ( { done, value } ) : any {
66
- if ( done ) {
67
- downloadComplete ;
68
- } else {
69
- writer . write ( value ) ;
70
- return reader . read ( ) . then ( readStuff ) ;
60
+ // Map the DOM's fetch Reader to node's streaming file system
61
+ // operations.
62
+ const downloadPromise = new Promise < void > (
63
+ ( downloadComplete , downloadFailed ) => {
64
+ fetch ( this . binaryUrl )
65
+ . then ( resp => {
66
+ if ( resp . status !== 200 ) {
67
+ console . log ( 'Download of emulator failed: ' , resp . statusText ) ;
68
+ downloadFailed ( ) ;
71
69
}
70
+ const reader = resp . body ?. getReader ( ) ;
71
+ reader ?. read ( ) . then ( function readChunk ( { done, value } ) : any {
72
+ if ( done ) {
73
+ downloadComplete ( ) ;
74
+ } else {
75
+ writer . write ( value ) ;
76
+ return reader . read ( ) . then ( readChunk ) ;
77
+ }
78
+ } ) ;
79
+ } )
80
+ . catch ( e => {
81
+ console . log ( `Download of emulator failed: ${ e } ` ) ;
82
+ downloadFailed ( ) ;
72
83
} ) ;
73
- } ) ;
74
- } catch ( e ) {
75
- console . log ( `Download of emulator failed: ${ e } ` ) ;
76
- downloadFailed ( ) ;
77
84
}
78
- } ) ;
79
- downloadPromise . then ( ( ) => {
80
- this . binaryPath = filepath ;
81
- if ( this . copyToCache ( ) ) {
82
- console . log ( `Cached emulator at ${ this . cacheBinaryPath } ` ) ;
85
+ ) ;
86
+ // Copy to cache when the download completes, and resolve
87
+ // the promise returned by this method.
88
+ downloadPromise . then (
89
+ ( ) => {
90
+ console . log ( 'Download complete' ) ;
91
+ this . binaryPath = filepath ;
92
+ if ( this . copyToCache ( ) ) {
93
+ console . log ( `Cached emulator at ${ this . cacheBinaryPath } ` ) ;
94
+ }
95
+ resolve ( ) ;
96
+ } ,
97
+ ( ) => {
98
+ reject ( ) ;
83
99
}
84
- resolve ;
85
- } , ( ) => {
86
- reject ;
87
- } ) ;
100
+ ) ;
88
101
} ) ;
89
102
} ) ;
90
103
}
0 commit comments