我试图使用nodejs在外壳中执行一些命令。因此,我使用节点:child_process
模块。
我使用 Spawn
函数,以便能够将子进程的输出转发到主过程的控制台。
为了保持子流程输出的格式,我通过了选项 stdio:“ sashit”
(如本问题所述:时,保留颜色时,请保存颜色)。
但是,如果我添加此选项,则儿童进程事件(退出,断开连接,关闭,...)不再起作用。如果我摆脱了选项,我会失去格式,但是事件可以工作。有没有一种方法可以保持格式化并在孩子关闭时通知?
(相关)代码:
const { spawn } = require("node:child_process");
let child = spawn("yarn", args, {
stdio: "inherit",
shell: true,
});
child.on("close", (code) => {
console.log(`child process exited with code ${code}`);
});
I am trying to execute some commands in the shell using NodeJS. Therefore I use the node:child_process
module.
I use the spawn
function in order to be able to forward the output of the child process to the console of the main process.
In order to keep the formatting of the output of the child process I passed the option stdio: "inherit"
(as described in this question: preserve color when executing child_process.spawn).
But if I add this option the child process events (exit, disconnect, close, ...) don't work anymore. If I get rid of the option I lose the formatting, but the events work. Is there a way to keep the formatting and be informed, when the child process closes?
The (relevant) code:
const { spawn } = require("node:child_process");
let child = spawn("yarn", args, {
stdio: "inherit",
shell: true,
});
child.on("close", (code) => {
console.log(`child process exited with code ${code}`);
});
发布评论
评论(1)
stdio:'sashit'
表示您还将stdin转发到子过程中,因此,如果子进程读取stdin,它将永远不会退出,并且您的close> close
侦听器将永远不会被打电话。特别是,node.js dept(yarn节点
)就是这种情况。根据您的需求,您可能需要:
child.kill()
停止子进程。然后调用关闭
侦听器,请注意代码
是0,第二个参数(Signal
)为sigterm
( documentation );spawn
使用stdio:['忽略','sashit','sashit']
(文档)。当子进程本身会退出并发布的流时,关闭
侦听器将被调用。stdio: 'inherit'
means you're also forwarding your STDIN to the child process, therefore if the child process reads STDIN, it will never exit, and yourclose
listener will never be called. In particular, that's the case for Node.JS REPL (yarn node
).Depending on your needs, you may want to:
child.kill()
. Theclose
listener is then called, note thatcode
is 0, and the second argument (signal
) isSIGTERM
(documentation);spawn
withstdio: ['ignore', 'inherit', 'inherit']
(documentation). When the child process will exit by itself and the streams released, theclose
listener will be called.