如何通过 NodeJS 子进程运行命令? [英] How to run commands via NodeJS child process?

查看:32
本文介绍了如何通过 NodeJS 子进程运行命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 NodeJS 子进程在 Windows 上运行命令:

I am trying to run commands on Windows via NodeJS child processes:

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 的回复.

When it calls ti.stdin.write, it writes it to the stdin descriptor, but how do I trigger cmd to react at this point? How do I send the "enter" key signal that you do when you are actually typing in command prompt? Currently I get no response from cmd.

推荐答案

发送换行符 将执行命令..end() 将退出 shell.

Sending a newline will exectue the command. .end() will exit the shell.

我修改了示例以在 osx 上使用 bash.

I modified the example to work with bash as I'm on 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:"
');
    terminal.stdin.write('uptime
');
    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

这篇关于如何通过 NodeJS 子进程运行命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆