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

发布于 2025-02-06 08:02:15 字数 665 浏览 2 评论 0 原文

我试图使用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}`);
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故人爱我别走 2025-02-13 08:02:15

stdio:'sashit'表示您还将stdin转发到子过程中,因此,如果子进程读取stdin,它将永远不会退出,并且您的 close> close 侦听器将永远不会被打电话。特别是,node.js dept( yarn节点)就是这种情况。

根据您的需求,您可能需要:

  1. 只需使用 child.kill()停止子进程。然后调用关闭侦听器,请注意代码是0,第二个参数( Signal )为 sigterm documentation );
  2. 请勿转发STDIN,但仍会转发stdout和stderr回头:call 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 your close 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:

  1. just stop the child process with child.kill(). The close listener is then called, note that code is 0, and the second argument (signal) is SIGTERM (documentation);
  2. do not forward STDIN but still forward STDOUT and STDERR back: call spawn with stdio: ['ignore', 'inherit', 'inherit'] (documentation). When the child process will exit by itself and the streams released, the close listener will be called.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文