2011-12-05 30 views
26

Tôi cố gắng để chạy lệnh trên Windows thông qua tiến trình con NodeJS:Làm thế nào để chạy các lệnh thông qua quá trình con NodeJS?

var terminal = require('child_process').spawn('cmd'); 

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

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

terminal.on('exit', function (code) { 
    console.log('child process exited with code ' + code); 
}); 

setTimeout(function() { 
    terminal.stdin.write('echo %PATH%'); 
}, 2000); 

Khi nó gọi ti.stdin.write, nó viết nó vào mô tả stdin, nhưng làm thế nào để kích hoạt cmd phản ứng vào thời điểm này? Làm cách nào để gửi tín hiệu khóa "enter" mà bạn thực hiện khi bạn đang gõ dấu nhắc lệnh? Hiện tại tôi không nhận được phản hồi từ cmd.

Trả lời

34

Gửi một dòng mới \n sẽ thoát lệnh. .end() sẽ thoát khỏi trình bao.

Tôi đã sửa đổi ví dụ để làm việc với bash khi tôi đang sử dụng osx.

var terminal = require('child_process').spawn('bash'); 

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

terminal.on('exit', function (code) { 
    console.log('child process exited with code ' + code); 
}); 

setTimeout(function() { 
    console.log('Sending stdin to terminal'); 
    terminal.stdin.write('echo "Hello $USER. Your machine runs since:"\n'); 
    terminal.stdin.write('uptime\n'); 
    console.log('Ending terminal session'); 
    terminal.stdin.end(); 
}, 1000); 

Kết quả sẽ là:

Sending stdin to terminal 
Ending terminal session 
stdout: Hello root. Your machine runs since: 
stdout: 9:47 up 50 mins, 2 users, load averages: 1.75 1.58 1.42 
child process exited with code 0 
24

Bạn chỉ cần gửi dòng cuối (\ n) bằng lệnh:

setTimeout(function() { 
    terminal.stdin.write('echo %PATH%\n'); 
}, 2000); 
+3

+1 @Raivo Laanemets - đây là câu trả lời thực tế cho câu hỏi của op. Trong khi bạn cần đến một lúc nào đó, hãy gọi 'stdin.end()' nếu bạn muốn xử lý nhiều đọc/phản hồi, bạn chỉ nên kết thúc bằng một dòng mới ('\ n' hoạt động trên windows xp/7) –

+0

Câu trả lời của Ravio là nhiều hơn liên quan, thích hợp – ShrekOverflow

4

Hãy chắc chắn rằng bạn stdin.end() tại một số điểm hoặc quá trình con sẽ không thoát.

6

Bạn có thể sử dụng phương pháp exec child_process. đây là ví dụ:

var exec = require('child_process').exec, 
    child; 

child = exec('echo %PATH%', 
    function (error, stdout, stderr) { 
     if(stdout!==''){ 
      console.log('---------stdout: ---------\n' + stdout); 
     } 
     if(stderr!==''){ 
      console.log('---------stderr: ---------\n' + stderr); 
     } 
     if (error !== null) { 
      console.log('---------exec error: ---------\n[' + error+']'); 
     } 
    }); 
Các vấn đề liên quan