Reputation: 165
var cp = require("child_process");
var proc = cp.spawn("cmd");
proc.stdout.on("data", data => console.log("Data:", data.toString()));
proc.stdin.write("help\n");
proc.stdin.write("help\n");
In the above code snippet, how would you detect when the stream has finished writing for a specific command (i.e. when, if these commands were executed in the terminal, it would show a blinking cursor that you could enter text into)?
I have tried using listening to the event end
, but this seems only to be fired when the process finishes.
Upvotes: 2
Views: 1623
Reputation: 81801
Pretty sure you can just do this:
proc.stdout.on('end', () => { /* we're done here */ })
Upvotes: 0
Reputation: 165
This can be solved by giving stdin a string which will be echoed back to you when the original command has been executed, where you know that the string executed have no unwanted effects and will probably not be outputted into stdout with the output of the command e.g. for the given example:
var cp = require("child_process");
var proc = cp.spawn("cmd");
proc.stdout.on("data", data => {
var str = data.toString();
console.log(str)
if(str.search("string to be detected") !== -1){
console.log("Command finished!");
}
});
proc.stdin.write("help\n");
proc.stdin.write("string to be detected\n");
Alternatively you could wait for some feature of the response which indicates the end of the command output such as a newline or a new prompt, as suggested by @mesdex and @user866762
Upvotes: 0
Reputation: 106696
There is no definitive way to know, unless the program you're executing has a well-defined output format (e.g. newline-delimited JSON, XML, etc.). Either way, you will have to perform some kind of parsing (and possible buffering) of the program output.
Upvotes: 1