问题描述
我正在尝试使用 child_process
模块和树莓派上的mpg123播放器在node.js中制作mp3网络广播.
I'm trying to make a mp3 webradio in node.js using the child_process
module and the mpg123 player on a raspberry pi.
这是问题所在:当我尝试写入流时,总是出现错误:
Here's the problem:When I try to write to a stream, I always get an Error:
Error: write EPIPE
at exports._errnoException (util.js:1026:11)
at WriteWrap.afterWrite (net.js:795:14)
这是我尝试测试的内容:
Here's what I tried to test it:
//create a subprocess
var test = childProcess.exec('ls /home/pi/music');
//pipe all the output to the process output
test.stdout.pipe(process.stdout);
test.stderr.pipe(process.stderr);
test.stdin.setEncoding('utf-8');
//here I just want to write a key to the subprocess
test.stdin.write('q');
test.stdin.end()
任何人都知道该怎么办,直到完成所有操作后,创建的写流才会关闭?
Anyone know, what to do, that the created write stream will not be closed until everything is done?
当然,我仍然在Google上搜索了此内容:
And of course I still searched on google for this:
https://github.com/nodejs/node/issues/2985
https://nodejs.org/api/child_process.html#child_process_subprocess_stdin
https://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback
请帮助!
推荐答案
EPIPE
写入错误表示某人正在写入管道,没人会读取.
The EPIPE
write error means someone is writing into a pipe that no one will ever read from.
此外,由于此错误是在没有人处理的上下文中引发的,因此该错误对于您的过程是致命的.可悲的是,node并不能很好地识别哪个流,但是我们可以猜测它在您的代码中,并且此代码仅写入了一个流...
Additionally, because this error is being raised in a context where no one handles it, the error is fatal for your process. Sadly, node doesn't do a good job of identifying which stream, but we can guess that its in your code, and there is only one stream being written to by this code ...
如果添加错误处理程序,则可以验证错误是否来自"stdin"流:test.stdin.on('错误',(... args)=> {console.log('stdin err',args);});
You can verify that the error is coming from the "stdin" stream if you add an error handler:test.stdin.on('error', (...args) => { console.log('stdin err', args); });
现在,错误(较差)将被处理",并且该过程将继续,因此您至少知道错误的出处.
Now the error will be "handled" (poorly), and the process will continue, so you at least know where its coming from.
具体来说,此 test.stdin.write('q')
正在将 q
写入流程的标准输入.但是您的子进程是 ls
.它在stdin上不接受任何内容,因此关闭了stdin.因此,当父级尝试写入现在关闭的管道时,操作系统会发回EPIPE错误.因此,请停止这样做.
Specifically this test.stdin.write('q')
is writing a q
to the stdin of your process. But your child process is ls
. It doesn't accept anything on stdin, so it closes stdin. So the OS sends an EPIPE error back when the parent tries to write to the now-closed pipe. So, stop doing that.
您可能希望 ls
与以交互方式键入 ls
时的行为相同,但可能不会(我怀疑您的交互式 ls
正在通过一个寻呼机,并且您期望要退出该寻呼机?)此子进程更像是交互式运行/bin/ls
.
You probably expect ls
to behave the same as when you type ls
interactively, but it probably does not (I suspect your interactive ls
is going through a pager, and you're expecting that you need to quit that pager?) This child process is more equivalent to running /bin/ls
interactively.
这篇关于Node.js写入子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!