Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node js interact with shell application

There are plenty of node js examples on online about how to spawn a child process and then catch the result as a string for your own processing.

But...

I want to 'interact' with a child process. For example, how would I write a node js application than starts by calling 'python' and then types a statement '1+1', lets me catch the result '2', before proceeding to type another arbitrary statement '4+4'?

(And by 'type' I'm assuming it will require streaming data to the stdin that the process uses).

like image 763
Trindaz Avatar asked Jun 05 '12 17:06

Trindaz


People also ask

How do I run a shell script in NodeJS?

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.

Is an interactive shell that processes node?

The Node. js Read-Eval-Print-Loop (REPL) is an interactive shell that processes Node. js expressions. The shell reads JavaScript code the user enters, evaluates the result of interpreting the line of code, prints the result to the user, and loops until the user signals to quit.


1 Answers

var child = require('child_process');
var ps = child.spawn('python', ['-i']);
ps.stdout.pipe(process.stdout);
ps.stdin.write('1+1');
ps.stdin.end();

works a treat!

like image 130
Trindaz Avatar answered Oct 02 '22 10:10

Trindaz