如何在 node.js 中关闭子进程的 stdio 管道

How to close the stdio pipes of child-processes in node.js?

本文关键字:子进程 stdio 管道 node js      更新时间:2023-09-26

我需要从node生成一个子进程.js并观察其stdout一段时间,然后关闭管道(以便节点进程可以终止)。

这是我的基本代码(不会终止节点进程):

const childProcess = require("child_process");
const child = childProcess.spawn("httpserver");
child.stdout.on("data", (data) => {
  console.log("child> " + data);
  // Disconnect Now ... How?
});

我已经尝试了以下方法:

  • 使用detached:true选项并调用child.unref()
  • 删除"数据"侦听器

具有上述更改但仍然不起作用的代码:

const child = childProcess.spawn("httpserver", [], {detached: true});
child.stdout.on("data", function cb(data) {
  console.log("child> " + data);
  child.stdout.removeListener("data", cb);
});
child.unref();

有没有其他方法可以关闭stdout管道,并断开与子进程的连接?


有点相关:文档提到了一个child.disconnect() API,但是当我在上面使用它时,我收到一个函数未找到错误。它是在这里使用的正确 API 吗,为什么在我的情况下不可用?

这个对我有用。

const fs = require('fs');
const spawn = require('child_process').spawn;
const out = fs.openSync('./out.log', 'a');
const err = fs.openSync('./out.log', 'a');
const child = spawn('prg', [], {
   detached: true,
   stdio: [ 'ignore', out, err ]
});
child.unref();

https://nodejs.org/api/child_process.html#child_process_options_detached