-
Notifications
You must be signed in to change notification settings - Fork 358
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Introduce
observeAsync
helper to improve async error handling
- Loading branch information
1 parent
444e8fe
commit 04d97d8
Showing
7 changed files
with
185 additions
and
184 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import * as fs from './fs' | ||
import { Observable } from 'rxjs' | ||
import followRedirects = require('follow-redirects') | ||
const { https } = followRedirects | ||
|
||
export default function downloadFile(url: string, path: string) { | ||
return new Observable(subscriber => { | ||
https.get(url, response => { | ||
if (response.statusCode !== 200) { | ||
const error = new Error(`The URL "${url}" returned status code ${response.statusCode}, expected 200.`) | ||
|
||
// Cancel download with error | ||
response.destroy(error) | ||
} | ||
|
||
const fileStream = fs.createWriteStream(path) | ||
|
||
const totalLength = parseInt(response.headers['content-length']) | ||
let currentLength = 0 | ||
|
||
const reportProgress = () => { | ||
const percentage = currentLength / totalLength | ||
subscriber.next(`${(percentage * 100).toFixed(2)}% done (${formatBytes(currentLength)} / ${formatBytes(totalLength)} MB)`) | ||
} | ||
reportProgress() | ||
|
||
response.pipe(fileStream) | ||
|
||
response.on('data', (chunk: Buffer) => { | ||
currentLength += chunk.byteLength | ||
reportProgress() | ||
}) | ||
response.on('error', error => subscriber.error(error)) | ||
|
||
fileStream.on('close', () => subscriber.complete()) | ||
}).on('error', error => subscriber.error(error)) | ||
}) | ||
} | ||
|
||
function formatBytes(bytes: number) { | ||
return (bytes / 1000000).toFixed(2) | ||
} |
Oops, something went wrong.