0

我需要运行一个子进程,然后它将在后台运行;同时,我想操纵它的输出(添加时间戳等)并将其重定向到特定文件。目前我正在这样做:

try {
  var out = fs.createWriteStream(`${this.logdir}/${lp}-out.log`, { flags: 'a', defaultEncoding: 'utf8' } );
  var err = fs.createWriteStream(`${this.logdir}/${lp}-err.log`, { flags: 'a', defaultEncoding: 'utf8' } );
} catch( e ){
  console.log("Could not open log files for writing:", e );
  return;
}

try {
  var child = childProcess.spawn( '/usr/bin/node', [ server ], { env: env, uid: uid, gid: gid, cwd: cwd } );
} catch( e ) {
  console.log("Could not run node:", e );
  return;
}

child.stdout.on('data', function( data ){

  try { 
    // The child process has stopped dealing with incoming connections.
    // For all intents and purposes, the process is useless and dead
    var d = data.toString();
    if( data.toString().match( /^THE SERVER HAS STOPPED$/m ) ){
      console.log("The child process has stopped taking connections!");
      try { fs.unlinkSync( pidFile ); } catch( e ){}
      dead = true;

      maybeRestart();
    }
    var pre = (new Date()).toString() + ' [' + child.pid + '] ';
    out.write( Buffer.from( data.toString().trim().split("\n").map( (l,i) => { return pre + l }) .join('\n') + '\n' ));
  } catch( e ){
    console.log("Error while redirecting stream to standard output!", e );
  }
});
child.stderr.on('data', function( data ){
  try {
    var pre = (new Date()).toString() + ' [' + child.pid + '] ';
    err.write( Buffer.from( data.toString().trim().split("\n").map( (l,i) => { return pre + l }) .join('\n') + '\n' ));
  } catch( e ){
    console.log("Error while redirecting stream to standard error!", e );
  }
});

问题:

  • 我是流的新手。我做对了吗?如果不是,那么这样做的“正确”方式是什么?
  • 我注意到流的“数据”回调中的错误不会冒泡——甚至不是UnexpectedErrors,因此是try {} catch {}语句。那是正确的方法吗?
4

1 回答 1

0

我不确定你到底需要什么。这取决于您的需求,如果 spawnSync 也是您的选择。如果您知道该过程不会花费很长时间并且您将直接获取标准输出,那就容易多了:https ://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options

于 2017-04-12T06:29:12.263 回答