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).
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With