31

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);

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.

Tower
  • 98,741
  • 129
  • 357
  • 507

4 Answers4

43

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

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);

The output will be:

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
Morgan G
  • 595
  • 1
  • 5
  • 19
toabi
  • 3,986
  • 1
  • 24
  • 24
27

You just have to send line end (\n) with the command:

setTimeout(function() {
    terminal.stdin.write('echo %PATH%\n');
}, 2000);
Raivo Laanemets
  • 1,119
  • 10
  • 7
  • 3
    +1 @Raivo Laanemets - this is the actual answer to the op's question. While you do need to at some point call the `stdin.end()` if you want to process multiple read / responses you should just terminate with a newline (`\n` works on windows xp / 7) – AJ. Mar 19 '12 at 16:41
6

You can use child_process exec method. here is an example:

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+']');
        }
    });
cuixiping
  • 24,167
  • 8
  • 82
  • 93
4

Make sure you stdin.end() at some point or the child process won't exit.

kgilpin
  • 2,201
  • 18
  • 18