j10
j10

Reputation: 2261

How to flush nodejs child_process stdin.write

I need to run a 'C' program for a client on the server side. this program can be interactive.
I am using Node.js child_process class. But I see a problem here : since I need to keep the program interactive there will be message exchanged back and forth between client and node.js server .

1.program says : Enter value of x :
send this message to client and get some value as input
2. When the Nodejs server receives the input from client it does child_process.stdin.write

But the problem is that the program does not execute until I mark the end of the stream. What could be a work around for this ?
Like flushing the values to the program as and when available from the user.

Update :

test1.c
#include

int main() {

int x, y;

printf("Enter x : ");
fflush(stdout);
scanf("%d", &x);

printf("Enter y : ");
fflush(stdout);
scanf("%d", &y);

printf("Value entered y is %d\n", y);
printf("Value entered x is %d", x);
}

Compile the above code to generate the executable a.out

var spawn = require('child_process').spawn;
var count = 0;
var exec = spawn('./a.out');


exec.on('error', function (err){
   console.log("Error" + err );
});

exec.stdout.on('data', function(data){
    console.log("in stdout.on.data : " + data.toString());
    if (count == 0) {
        exec.stdin.write('44\n');
        count++;
    }
    else if (count == 1) {
        exec.stdin.write('54');
        count++;
    }
    if (count == 2) {
        exec.stdin.end();
    }

});

exec.stderr.on('data', function(data) {
    console.log("in stderr.on.data : " + data);
});

exec.on('close', function (code) {
    if (code != 0) {
        console.log("Program ended with a error code : " + code);
    }

});

in the above node.js code if I comment exec.stdin.end(); it does not work and it waits until the stream is closed. How can I work around this ? since I want clients to have a continuous interaction it will be difficult for me to predict when to end the stream.

Upvotes: 3

Views: 4663

Answers (1)

vovchisko
vovchisko

Reputation: 2229

You forgot to "press Enter".

exec.stdin.write('54' + "\n");
OR
exec.stdin.write("54\n");

You also can lookup a bit about Quotes in JavaScript

Upvotes: 4

Related Questions