Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run commands via NodeJS child process?

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.

like image 565
Tower Avatar asked Dec 05 '11 18:12

Tower


People also ask

How do you execute a command in a child process?

Function execute() takes array argv[], treats it as a command line arguments with the program name in argv[0], forks a child process, and executes the indicated program in that child process. While the child process is executing the command, the parent executes a wait(), waiting for the completion of the child.

How do I run a command in node js?

Node. js can run shell commands by using the standard child_process module. If we use the exec() function, our command will run and its output will be available to us in a callback. If we use the spawn() module, its output will be available via event listeners.


2 Answers

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 
like image 178
toabi Avatar answered Sep 21 '22 15:09

toabi


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

setTimeout(function() {     terminal.stdin.write('echo %PATH%\n'); }, 2000); 
like image 24
Raivo Laanemets Avatar answered Sep 19 '22 15:09

Raivo Laanemets