2012-10-12 5 views
0

node.js에 관한 한 초보자입니다. 두 개의 linux 명령을 파이프 라인 처리하는 다음 코드를 작성했습니다.때때로 코드가 실패하고 가끔씩 실행됩니다.

var spawn = require('child_process').spawn, 
    ls = spawn('ls',['-lh','/usr']), 
    grep = spawn('grep',['bin']); 

/* 
ls.stdout.on('data',function(data){ 
    console.log('stdout: '+data); 
}); 
*/ 

ls.stdout.on('data',function(data){ 
    console.log(""+data); 
    grep.stdin.write(data); 
}); 

ls.stderr.on('data',function(data){ 
    console.log('stderr: '+data); 
}); 


ls.on('exit',function(code){ 
    console.log('Exit code '+code); 
    grep.stdin.end(); 
}) 

// ------------------------------------ 

grep.stdout.on('data',function(data){ 
    console.log('stdout: '+data); 
}); 

grep.stderr.on('data',function(data){ 
    console.log('stderr: '+data); 
}); 

지금이 코드는 때때로 실패하고 번요 지금 혼란스러워지고 실행 : 이 내 nodejs 코드입니다.

Exit code 0 
total 160K 
drwxr-xr-x 2 root root 68K Oct 12 12:54 bin 
drwxr-xr-x 2 root root 4.0K Jun 20 19:58 games 
drwxr-xr-x 54 root root 4.0K Sep 24 17:52 include 
drwxr-xr-x 252 root root 44K Oct 2 21:53 lib 
drwxr-xr-x 10 root root 4.0K Apr 28 19:16 local 
drwxr-xr-x 2 root root 12K Sep 18 15:51 sbin 
drwxr-xr-x 362 root root 12K Sep 28 17:58 share 
drwxr-xr-x 5 root root 4.0K Jul 7 23:39 src 


events.js:66 
     throw arguments[1]; // Unhandled 'error' event 
        ^
Error: This socket is closed. 
    at Socket._write (net.js:517:19) 
    at Socket.write (net.js:509:15) 
    at Socket.<anonymous> (/home/rajat/nodexperiments/full-spawn.js:13:13) 
    at Socket.EventEmitter.emit (events.js:88:17) 
    at Pipe.onread (net.js:395:14) 

를 그리고이 실행될 때, 그것은 말한다 : 실패하면 , 그것은 말한다

total 160K 
drwxr-xr-x 2 root root 68K Oct 12 12:54 bin 
drwxr-xr-x 2 root root 4.0K Jun 20 19:58 games 
drwxr-xr-x 54 root root 4.0K Sep 24 17:52 include 
drwxr-xr-x 252 root root 44K Oct 2 21:53 lib 
drwxr-xr-x 10 root root 4.0K Apr 28 19:16 local 
drwxr-xr-x 2 root root 12K Sep 18 15:51 sbin 
drwxr-xr-x 362 root root 12K Sep 28 17:58 share 
drwxr-xr-x 5 root root 4.0K Jul 7 23:39 src 

Exit code 0 
stdout: drwxr-xr-x 2 root root 68K Oct 12 12:54 bin 
drwxr-xr-x 2 root root 12K Sep 18 15:51 sbin 

어떤 아이디어?

+0

'ls.stdout'과 관련된 모든 것을'ls.stdout.pipe (grep.stdin)'로 바꾸면 어떻게 될까요? – ebohlman

답변

0

node.js가 매우 평행 한 환경이기 때문에 이것은 아주 분명히 경쟁 조건입니다. 이 그렙에 작성 완료 후 통신에 사용되고있는 소켓을 종료하기 전에

ls.on('exit',function(code){ 
    console.log('Exit code '+code); 
    grep.stdin.end(); 
}) 

LS는, 위의 이벤트가 발생합니다. 출력 결과는 ls에서 나오는 exit (0) 메시지가 출력 상단에 한 번 나타나고 오류 메시지 바로 위에 표시된다는 힌트를 제공합니다.

여기에서 grep의 stdin 채널을 닫지 마십시오.

그러나 이벤트와 다음

#/bin/bash mybashscript 
ls $1 | grep bin 

와 자바 스크립트 클로저를 사용하여 같은과 같은

child = exec('mybashscript',['-lh','/usr'] 
    function (error, stdout, stderr) { 
    console.log('stdout: ' + stdout); 
    console.log('stderr: ' + stderr); 
    if (error !== null) { 
     console.log('exec error: ' + error); 
    } 
}); 

을하는 bash는 스크립트 대신 산란의) (.exec 사용에 대해 코드 순서는 읽기가 더 어렵습니다.

관련 문제