Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: write EPIPE when piping node output to "| head"

Tags:

node.js

stdout

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?

like image 738
Fluffy Avatar asked Sep 08 '12 10:09

Fluffy


2 Answers

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);     } }); 
like image 112
Jim Avatar answered Sep 28 '22 05:09

Jim


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.

like image 36
David Schwartz Avatar answered Sep 28 '22 05:09

David Schwartz