My main Node.js process spawns a child process. I want to communicate to the child process by sending it data through its stdin and reading it out from its stdout. The child process will continue running. I want to send it a message, then wait for it to respond, do something with the response, and then continue the main process. How do I best do this? I tried the following:
// I call this function after sending to child's stdin
private async readWaitStream() {
let data = '';
let chunk = '';
while (chunk = this._child.stdout.read()){
data += chunk;
}
// doesn't finish because child process stays running
await finished(this._child.stdout);
return data;
}
The child process never finishes, and this doesn't work.
I figured out how to solve the problem. I use once.('readable' ... )
, for example:
private readWaitStream() {
return new Promise(resolve => {
let data = '';
this._child.once('readable', () => {
let chunk = '';
while (chunk = this._child.read()) {
data += chunk;
}
resolve(data);
});
});
}
When I then
the function, we will wait for input and the promise will only resolve after the next input is available.