小编Jak*_*ger的帖子

NodeJS child_process:指定 stdio 时未触发关闭事件:“继承”

我正在尝试使用 NodeJS 在 shell 中执行一些命令。因此我使用该node:child_process模块。

我使用该spawn函数是为了能够将子进程的输出转发到主进程的控制台。为了保持子进程输出的格式,我传递了该选项stdio: "inherit"(如本问题所述:在执行 child_process.spawn 时保留颜色)。

但如果我添加此选项,子进程事件(退出、断开连接、关闭……)将不再起作用。如果我删除该选项,我会丢失格式,但事件会起作用。有没有办法在子进程关闭时保留格式并得到通知?

(相关)代码:

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}`);
});
Run Code Online (Sandbox Code Playgroud)

stdio child-process node.js

2
推荐指数
1
解决办法
1451
查看次数

标签 统计

child-process ×1

node.js ×1

stdio ×1