一尘不染

如何通过NodeJS子进程运行命令?

node.js

我正在尝试通过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);
});

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


阅读 327

收藏
2020-07-07

共1个答案

一尘不染

发送换行符\n将执行该命令。.end()将退出外壳。

我在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
2020-07-07