3

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 calling child.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?

HRJ
  • 17,079
  • 11
  • 56
  • 80
  • this can help http://stackoverflow.com/questions/20187184/how-to-kill-childprocess-in-nodejs – AshBringer Feb 12 '16 at 08:26
  • @BipBip I don't want to kill the child process. I need to keep it running and "detach" the node-process from it. – HRJ Feb 12 '16 at 08:31

1 Answers1

1

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

Royal Pinto
  • 2,869
  • 8
  • 27
  • 39
  • This works, thanks! One minor niggle is that watching files for changes is not reliable across OSes and filesystems. But this is a good starting point to explore more. Thx again. – HRJ Feb 13 '16 at 05:46