Skip to content

Instantly share code, notes, and snippets.

@mhart
Created May 3, 2012 13:34
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mhart/2585671 to your computer and use it in GitHub Desktop.
Save mhart/2585671 to your computer and use it in GitHub Desktop.
stdin/stdout pipe in node.js
// 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)
})
// 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