2017-12-05 18 views
2

, 나는 내가 킬 (kill) 프로그램은 아마도 출력이 표준 출력으로 여기 캡처 할 수없는 자식 프로세스를 시작 발견Node.js에서 콘솔 출력을 캡처 할 수 있습니까? 내가 처음에 프로세스를 종료하려고

exec = require('child_process').exec; 
exec('kill xxx', function(error, stdout, stderr) { 
    if (error) { 
     console.log('exec error: ', error); 
    }else{ 
     console.log(stdout) 
    } 
}); 

으로 실행.

그래서 일반적으로 코드와 관련성이없는 콘솔 출력을 캡처 할 수 있습니까?

+4

의 사용 가능한 복제 [노드가 : 대신 콘솔의 파일에 로그인 (https://stackoverflow.com/questions/8393636/node-log-in-a-file-of-the-console) –

답변

3

도난 : Node: log in a file instead of the console

var fs = require('fs'); 
var util = require('util'); 
var log_file = fs.createWriteStream(__dirname + '/debug.log', {flags : 'w'}); 
var log_stdout = process.stdout; 

console.log = function(d) { // 
    log_file.write(util.format(d) + '\n'); 
    log_stdout.write(util.format(d) + '\n'); 
}; 

답변 # 2 이 메시지는 오히려 단지 리눅스 시스템 자체를 CONSOLE.LOG에 의해 만들어지지 않습니다. 이걸 잡는 법? 난 당신이 너무 좋아 FS와 함께 뭔가를 할 수 있어야한다고 생각

...

var fs = require('fs'); 
    var util = require('util'); 
    var log_file = fs.createWriteStream(__dirname + '/debug.log', {flags : 'w'}); 
    var log_stdout = process.stdout; 

const command = 'node your_node_script'; //Whatever you would run in terminal 

cp.exec(command, (error, stdout, stderr) => { 
    if(error) { 
     log_file.write(error); 

    } 
    if(stdout) { 
     log_file.write(stdout); 
    } 
    if(stderr) { 
     log_file.write(stderr); 
    } 
}); 
+0

음, 문제가 있습니다. console.log에서 콘솔 출력을 만들 필요는 없습니다. 예 : 내가 프로세스를 죽였을 때, 2 초 동안 기다리면, 콘솔은 "xxx terminated"메시지를 생성 할 것입니다. 이 메시지는 Linux 시스템 자체가 아닌 console.log에 의해 작성됩니다. 이걸 잡는 법? –

+0

시도해 볼 제안 사항이 업데이트되었습니다. –