Shell 如何通过NodeJS子进程运行命令?
我正在尝试通过NodeJS子进程在Windows上运行命令:Shell 如何通过NodeJS子进程运行命令?,shell,node.js,process,command-line-interface,command-prompt,Shell,Node.js,Process,Command Line Interface,Command Prompt,我正在尝试通过NodeJS子进程在Windows上运行命令: 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
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);
当调用
ti.stdin.write
时,它会将其写入stdin
描述符,但此时如何触发cmd
作出反应?当您实际在命令提示符中键入时,如何发送“回车”键信号?当前我没有收到来自cmd
的响应,发送新行\n
将执行该命令.end()
将退出shell
当我在osx上工作时,我修改了这个示例以使用bash
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);
输出将是:
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
您只需使用以下命令发送行结束(\n):
setTimeout(function() {
terminal.stdin.write('echo %PATH%\n');
}, 2000);
请确保在某个时刻执行stdin.end(),否则子进程将不会退出。您可以使用child\u process exec方法。 以下是一个例子:
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+']');
}
});
+1@Raivo Laanemets-这是op问题的实际答案。虽然您确实需要在某个时候调用
stdin.end()