Skip to content

Instantly share code, notes, and snippets.

@mooyoul
Created February 19, 2017 18:49
Show Gist options
  • Save mooyoul/cdfc66bf0613daa77022e84e92b1899e to your computer and use it in GitHub Desktop.
Save mooyoul/cdfc66bf0613daa77022e84e92b1899e to your computer and use it in GitHub Desktop.
store-local-file-delayed-http.js
'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