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

查看:450
本文介绍了如何通过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.

推荐答案

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

Sending a newline \n 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:"\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

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

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