gpt4 book ai didi

javascript - Node.js 写入子进程

转载 作者:太空宇宙 更新时间:2023-11-04 01:56:47 24 4
gpt4 key购买 nike

我正在尝试使用 child_process 模块和树莓派上的 mpg123 播放器在 node.js 中制作 mp3 webradio。

问题是这样的:当我尝试写入流时,我总是收到错误:

Error: write EPIPE
at exports._errnoException (util.js:1026:11)
at WriteWrap.afterWrite (net.js:795:14)

这是我尝试测试的内容:

//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()

有人知道该怎么做,在一切完成之前创建的写入流不会关闭吗?

当然我仍然在谷歌上搜索这个:

Child_process throw an Error: write EPIPE

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 写入错误意味着有人正在向无人读取的管道写入数据。

此外,由于此错误是在无人处理的上下文中引发的,因此该错误对于您的进程来说是致命的。遗憾的是, Node 在识别哪个流方面做得不好,但我们可以猜测它在您的代码中,并且此代码只写入一个流......

如果添加错误处理程序,您可以验证错误是否来自“stdin”流:
test.stdin.on('错误', (...args) => { console.log('stdin err', args); });

现在错误将被“处理”(很差),并且该过程将继续,因此您至少知道它来自哪里。

具体来说,这个 test.stdin.write('q') 正在将 q 写入进程的标准输入。但你的子进程是ls。它不接受标准输入上的任何内容,因此它关闭标准输入。因此,当父进程尝试写入现已关闭的管道时,操作系统会发回 EPIPE 错误。所以,停止这样做。

您可能期望 ls 的行为与交互式键入 ls 时相同,但事实可能并非如此(我怀疑您的交互式 ls 正在通过寻呼机,而您希望需要退出该寻呼机?)此子进程更相当于交互式运行 /bin/ls

关于javascript - Node.js 写入子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47651865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com