I'm having problems with getting the error:
events.js:48 throw arguments[1]; // Unhandled 'error' event ^ Error: write EPIPE at errnoException (net.js:670:11) at Object.afterWrite [as oncomplete] (net.js:503:19)
when piping output to head. A simple case to try it out is:
console.log('some string'); ... the same for 20 lines
and then node test.js | head
to get the error, which seems to appear in about 70% runs on Ubuntu 12.04. What's the problem?
To alter the program to exit successfully in the case of a closed pipe, try:
process.stdout.on('error', function( err ) { if (err.code == "EPIPE") { process.exit(0); } });
The head
command only reads the first few lines. Your code expects all of its output to be read and triggers an error if it cannot produce output. If it is legal to throw away output from your program, don't treat it as a fatal error in the program. If it's not legal to throw away output from your program, don't pipe it to head
.
You currently have a race condition. If head
begins ignoring input before the program finishes writing its output, the program gets an exception. If the program finishes writing its output before head
begins ignoring its input, everything is fine.
As a silly temporary fix: node test.js | tee /dev/null | head
Now, tee
will take all the program's output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With