HRJ
HRJ

Reputation: 17777

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

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:

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?

Upvotes: 3

Views: 3330

Answers (1)

Royal Pinto
Royal Pinto

Reputation: 2911

This one worked for me.

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

Upvotes: 1

Related Questions