Created
May 3, 2012 13:34
-
-
Save mhart/2585671 to your computer and use it in GitHub Desktop.
stdin/stdout pipe in node.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
// So this is short and easier | |
process.stdin.resume() | |
process.stdin.on('data', function(data) { process.stdout.write(data) }) | |
process.stdout.on('error', function(err) { | |
if (err.code === 'EPIPE') return process.exit() | |
process.emit('error', err) | |
}) |
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
// But is this more "correct"? | |
process.stdin.resume() | |
process.stdin.on('data', function(data) { process.stdout.write(data) }) | |
process.stdout.on('error', function epipeFilter(err) { | |
if (err.code === 'EPIPE') return process.exit() | |
// If there's more than one error handler (ie, us), then the error won't be bubbled up anyway | |
if (process.stdout.listeners('error').length <= 1) { | |
process.stdout.removeAllListeners() // Pretend we were never here | |
process.stdout.emit('error', err) // Then emit as if we were never here | |
process.stdout.on('error', epipeFilter) // Then reattach, ready for the next error! | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment