Created
February 19, 2017 18:00
-
-
Save mooyoul/22c30bc04aff53190564c63a6484da1e to your computer and use it in GitHub Desktop.
store-local-file-delayed.js
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
'use strict'; | |
const request = require('request'); | |
const fs = require('fs'); | |
// fetch binary from `url` and upload to local file using `dest` as destination | |
const store = (url, dest) => { | |
return new Promise((resolve, reject) => { | |
request({ | |
method: 'GET', | |
url: url, | |
encoding: null // returns body as Buffer | |
}).on('error', (e) => { | |
// something went wrong during fetch avatar. | |
return reject(e); | |
}).on('response', (res) => { | |
if (res.statusCode.toString().slice(0, 1) !== '2') { // server respond with unexpected status code | |
return reject(new Error(`Unexpected status code ${res.statusCode}`)); | |
} | |
setTimeout(() => { | |
res.pipe(fs.createWriteStream(dest)) | |
.on('error', (e) => { | |
// something went wrong on writable stream | |
reject(e); | |
}).on('finish', () => { | |
// all data has been flushed | |
resolve(dest); | |
}); | |
}, 10); | |
}); | |
}); | |
}; | |
module.exports = exports = store; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment