I need to spawn a child process from node.js and observe its stdout for a while and then close the pipe (so that the node process can terminate).
Here's my base code (which doesn't terminate the node process):
const childProcess = require("child_process");
const child = childProcess.spawn("httpserver");
child.stdout.on("data", (data) => {
console.log("child> " + data);
// Disconnect Now ... How?
});
I have tried the following already:
- Using
detached:true
option and callingchild.unref()
- removing the "data" listener
Code with the above changes but still doesn't work:
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();
Is there any other way to close the stdout
pipe, and disconnect from the child-process?
Somewhat related: the documentation mentions a child.disconnect()
API but when I use it above, I get a function not found error. Is it the right API to use here and why isn't it available in my case?