Monday, 29 May 2017

How to send input to child process created with spawn? nodejs

I'm running Windows 10, and I have a program, let's call it program, that can be run from the command line. When run, it responds to commands the user enters. The user enters a command, presses the return key, and the program prints a response. I did not make this program and do not have the source, so I cannot modify it.

I want to run this program from within Node.js, and have my Node.js program act as the user, sending it commands and getting the responses. I spawn my program like this:

var spawn = require('child_process').spawn;
var child = spawn('program');

child.stdout.on('data', function(data) {
    console.log(`stdout: ${data}`);
});

Then I attempt to send it a command, for example, help.

child.stdin.write("help\n");

And nothing happens. If I manually run the program, type help, and press the return key, I get output. I want Node.js to run the program, send it input, and receive the output exactly as a human user would. I assumed that stdin.write() would send the program a command as if the user typed it in the console. However, as the program does not respond, I assume this is not the case. How can I send the program input?

I've seen many similar questions, but unfortunately the solutions their authors report as "working" did not work for me.



via user1465113

No comments:

Post a Comment