Last active
          November 3, 2016 18:34 
        
      - 
      
- 
        Save eschwartz/44a26ebca98864ffc7abff88163a8f79 to your computer and use it in GitHub Desktop. 
    Download File
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | /** | |
| * | |
| * @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); | |
| }) | |
| } | 
  
    
      This file contains hidden or 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
    
  
  
    
  | 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