2017-04-12 10 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이 아니기 때문에 try {} catch {} 문도 발생하지 않았습니다. 그게 올바른 길 이었습니까?

답변

0

정확히 필요한 것이 무엇인지 확실하지 않습니다. spawnSync가 옵션 인 경우 필요에 따라 약간 다릅니다. 프로세스가 오랜 시간이 걸리지 않을 것이고 직접 stdout을 얻을 수 있다는 것을 안다면 훨씬 쉽습니다. https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options

+0

아니요, 죄송합니다. 프로세스가 거의 영원히 돌아갈 것입니다 ... – Merc