I have a simple C++ program compiled using command gcc 1.cpp -o 1.exe
.
// 1.cpp
#include <stdio.h>
int main(){
int a = 0;
scanf("%d", &a);
printf("%d", a + 1000);
scanf("%d", &a);
printf("\n%d", a + 1000);
return 0;
}
My goal is to create Node.js application which will be able to pass one number to 1.exe
, then display result, and after that pass displayed result as next number. Finally, application must write second result and then close.
I've searched on Node.js manual's and documentations, and also on other sites, but I still cannot figure out how to create interactive child process in Node.js. The following code simply doesn't work.
var cp = require('child_process');
var proc = cp.spawn(pathToFile);
var n = 0;
proc.stdout.on('data', function(a){
process.stdout.write(a);
if(!n++) proc.stdin.write(a + '\n');
});
proc.stdin.write('1\n');
The function proc.stdout.on(data, ...)
will never be reached, because it is called only when child process exit. Problem is because it will exit when second number is passed, but second number is passed when first result is received. I've tried many combinations and many options in cp.spawn
function, but nothing worked as I expected.
The reason I want fully interactive child process is because I want to create Node.js module which use external application which requires a long time to load, so easier way is to keep child process active and just to send and receive data through stdio.
The C++ application is just an example. The real application I want Node.js to interact with is something I cannot edit, so do not expect from me to change the code of that application. I must adapt Node.js code to interact with application, not vice versa. When I execute external application with command prompt, I receive output after every input line, so it is not problem with that application.
Any ideas how to make fully interacting child process?