Created
February 19, 2017 18:49
-
-
Save mooyoul/cdfc66bf0613daa77022e84e92b1899e to your computer and use it in GitHub Desktop.
store-local-file-delayed-http.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 http = require('http'); | |
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) => { | |
http.get(url).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); | |
}); | |
}, 1000); | |
}); | |
}); | |
}; | |
module.exports = exports = store; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment