Skip to content

Instantly share code, notes, and snippets.

@eschwartz
Last active November 3, 2016 18:34
Show Gist options
  • Save eschwartz/44a26ebca98864ffc7abff88163a8f79 to your computer and use it in GitHub Desktop.
Save eschwartz/44a26ebca98864ffc7abff88163a8f79 to your computer and use it in GitHub Desktop.
Download File
/**
*
* @param {string|Object} reqOpts Url, or `request` options
* @param {string} destFile file path
* @throws ExternalServiceError
* @return {Promise}
*/
function download(reqOpts, destFile) {
return new Promise((resolve, reject) => {
request(reqOpts)
.on('response', res => {
if (res.statusCode >= 400) {
reject(new Error(`Request to ${res.request.uri.href} returned a ${res.statusCode}`));
}
})
.on('error', err => reject(new ExternalServiceError(err.message)))
.pipe(fs.createWriteStream(destFile))
.on('error', reject)
.on('finish', resolve);
})
}
import * as request from 'request';
import * as fs from 'fs';
type IReqOpts = request.RequiredUriUrl & request.CoreOptions;
function download(reqOpts: IReqOpts, destFile:string):Promise<void> {
return new Promise((resolve, reject) => {
request(reqOpts)
.on('response', res => {
if (res.statusCode >= 400) {
reject(new Error(`Request to ${(<any>res).request.uri.href} returned a ${res.statusCode}`));
}
})
.on('error', err => reject(new Error(err.message)))
.pipe(fs.createWriteStream(destFile))
.on('error', reject)
.on('finish', resolve);
})
}
export default download;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment