2017-04-12 88 views
0

我需要運行一個子進程,然後它將在後臺運行;同時,我想操縱它的輸出(添加時間戳等)並將其重定向到特定文件。 目前,我這樣做:運行一個進程並將stdin/strout重定向到特定文件

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); 
    } 
}); 

問題:

  • 我是新來的流。我做對了嗎?如果沒有,那麼做到這一點的「正確」方式是什麼?
  • 我注意到流的「數據」回調中的錯誤不會冒泡 - 甚至不是UnexpectedError s,因此try {} catch {}聲明。那是正確的路嗎?

回答

相關問題