node.js 错误:在管道节点输出到“| head”时写入 EPIPE
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12329816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error: write EPIPE when piping node output to "| head"
提问by Fluffy
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 | headto get the error, which seems to appear in about 70% runs on Ubuntu 12.04. What's the problem?
然后node test.js | head得到错误,它似乎出现在 Ubuntu 12.04 上运行的大约 70% 中。有什么问题?
采纳答案by David Schwartz
The headcommand 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.
该head命令仅读取前几行。您的代码希望读取其所有输出,如果无法生成输出,则会触发错误。如果丢弃程序的输出是合法的,请不要将其视为程序中的致命错误。如果从程序中丢弃输出是不合法的,请不要将其通过管道传输到head.
You currently have a race condition. If headbegins ignoring input before the program finishes writing its output, the program gets an exception. If the program finishes writing its output before headbegins ignoring its input, everything is fine.
您当前有竞争条件。如果head在程序写完输出之前开始忽略输入,程序就会得到一个异常。如果程序在head开始忽略其输入之前完成了其输出的写入,则一切正常。
As a silly temporary fix: node test.js | tee /dev/null | head
Now, teewill take all the program's output.
作为一个愚蠢的临时修复:node test.js | tee /dev/null | head
现在,tee将获取所有程序的输出。
回答by Jim
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);
}
});

