Skip to content

Instantly share code, notes, and snippets.

@boutell
Created April 18, 2013 01:31
Show Gist options
  • Save boutell/5409228 to your computer and use it in GitHub Desktop.
Save boutell/5409228 to your computer and use it in GitHub Desktop.
Piping a knox S3 http response (an input stream) to an output file, reliably detecting error and invoking a completion callback
var res = // Any input stream
var out = fs.createWriteStream(localPath);
res.pipe(out);
var dead = false;
function die(err) {
if (!dead) {
dead = true;
res.end();
out.end();
return callback(err);
}
}
res.on('error', function(err) {
return die(err);
});
out.on('error', function(err) {
return die(err);
});
out.on('end', function() {
if (!dead) {
return callback(null);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment