0
votes

I'm trying to initiate a few processes from a running Node.js process. The problem is, that these have to be initiated from a script, and using exec like this:

exec("./scripts/run.sh",(err, stdout, stderr)  => {
if (err) {
  console.error(err);
  return;
}
  this.logs = this.logs.unshift(timestamp() + stdout);
  this.errorlogs = this.logs.unshift(timestamp() + stderr);
});

Does not redirect the output I need. Fork seems to be only for Node.js processes which these are not.

The processes work just fine and do function as child processes of the main process. I just need to actually get the stdout and stderr outputs. Any suggestions?

1
Try stderr.on( 'data', console.log ) and stdout.on( 'data', console.log )? - somethinghere
Doesn't seem to output anything. Thank you though! - Lily

1 Answers

0
votes

child_process.exec() only runs the callback function once, after the exec'ed process has terminated. If you want incremental data from the stdout and stderr of the process while it is still running, use child_process.spawn() and set the options.stdio attribute to make the process's stdout and stderr available to the parent.

child_process.spawn() returns a ChildProcess object. To collect the process's output you can establish data handlers for that object's stdout and stderr streams. You should also establish handlers for the error event that fires if the process launch fails and the close event that fires when those streams have closed and the process has terminated.

It will look something like this:

  child = spawn("./scripts/run.sh", 
                [],
                {stdio: ['ignore', 'pipe', 'pipe']});

  child.on('error', (err) => }
      console.log('child launch failed: ', err);
  });

  child.on('close', (code) => {
      console.log('child ended: ', code);
  });

  child.stdout.on('data', (outdata) => {
      this.logs = this.logs.unshift(timestamp() + outdata);
  });

  child.stderr.on('data', (errdata) => {
      this.errorlogs = this.logs.unshift(timestamp() + errdata);
  });

The gory details are in the Node.js docs at https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_child_process_spawn_command_args_options and https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_class_childprocess