Подтвердить что ты не робот

Как выполнять команды через дочерний процесс NodeJS?

Я пытаюсь запустить команды в Windows через дочерние процессы 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);

Когда он вызывает ti.stdin.write, он записывает его в дескриптор stdin, но как мне активировать cmd для реагирования на данный момент? Как отправить сигнал клавиши "enter", который вы делаете, когда вы действительно вводите командную строку? В настоящее время я не получаю ответа от cmd.

4b9b3361

Ответ 1

Отправка новой строки \n приведет к вызову команды. .end() выйдет из оболочки.

Я изменил пример работы с bash, поскольку я нахожусь в 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

Ответ 2

Вам просто нужно отправить конец строки (\n) с помощью команды:

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

Ответ 3

Вы можете использовать метод child_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+']');
        }
    });

Ответ 4

В какой-то момент убедитесь, что вы stdin.end() или дочерний процесс не будет завершен.