Created
April 18, 2013 01:31
-
-
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
This file contains 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
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