如何closuresnode.js中subprocess的stdiopipe道?

我需要从node.js产生一个subprocess,观察它的标准输出一段时间,然后closurespipe道(这样节点进程可以终止)。

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

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

有没有其他方式来closuresstdoutpipe道,并从subprocess断开连接?


有点相关:文档提到了一个child.disconnect() API,但是当我在上面使用它,我得到一个函数未find错误。 这是在这里使用的正确的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