Use child_process to run an interactive program

29 views
Skip to first unread message

Claudio De Meo

unread,
Mar 27, 2018, 12:03:33 PM3/27/18
to nodejs
Hi,
is there a way to execute a child process that require an interactive input/output?
In practice I would like to run from nodejs a simple c/c++ program like this:

#include <stdio.h>
 
int main (){
  char str[100];
  printf("insert a string \n");
  scanf("%s",str);
  printf("the string is %s \n",str);
  return 0;
}

So the child process should ask me a string (first output), I type the string (first input) and then it show me the string (final output).

I tried in different way but there is no output...

For example I tried with spawn:

var spawn = require('child_process').spawn;
var proc = spawn('./my-program.exe');

proc.stdout.on('data', function(data){
  //print the output of program
  console.log(`${data}`);
})

//function to insert input
function insertInput(data){
  proc.stdin.setEncoding('utf-8');
  proc.stdin.write(data + '\n');
  proc.stdin.end();
}

or with exec:

var exec = require('child_process').exec;
var proc = exec('./my-program.exe', function(err, stdout, stderr){
  //print the output of program
  console.log(`${stdout}`);
});

//function to insert input
function insertInput(data){
  proc.stdin.setEncoding('utf-8');
  proc.stdin.write(data + '\n');
  proc.stdin.end();
}

It seems that it shows me all output only at the end of execution, but so I can not do input when it ask me.

Reply all
Reply to author
Forward
0 new messages