node js interact with shell application

2019-02-05 09:02发布

问题:

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

回答1:

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!