How to send input to a child process created using spawn? nodejs

I am running Windows 10, and I have a program, call her program, which can be launched from the command line. At startup, it responds to commands that the user enters. The user enters a command, presses the return key, and the program prints the response. I did not make this program and do not have a source, therefore I cannot change it.

I want to run this program from Node.js, and my Node.js program acts as a user, sends it and receives answers. I run my program as follows:

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

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

Then I try to send him a command, for example help.

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

. , help , . , Node.js , , . , stdin.write() , . , , , . ?

, , , , "", .

+8
2

. child_process exec . Promise /cmd . , .

, .

executeCLI("cat ~/index.html");

, aws cli.

executeCLI("aws configure --profile dev")

executeCLI.

var { exec } = require('child_process');
async function executeCLI(cmd) {
  console.log("About to execute this: ", cmd);
  var child = exec(cmd);
  return new Promise((resolve, reject) => {
    child.stdout.on('data', (data) => {
      console.log('${data}');
      process.stdin.pipe(child.stdin);
    });

    child.on('close', function (err, data) {
      if (err) {
        console.log("Error executing cmd: ", err);
        reject(err);
      } else {
        //   console.log("data:", data)
        resolve(data);
      }
    });
  });
}
0

fs. " program.cpp " .

c++ , g++, child_process .

execFile

var { execFile } = require('child_process');

execFile("g++", ['program.cpp'], (err, stdout, stderr) => {
    if (err) {
        console.log("compilation error: ",err);
    } else{
        execFile ('./a.out' ,['<', 'input.txt'], {shell: true}, (err, stdout, stderr) => {
            console.log("output: ", stdout);         
        })
    }
})

child_process execFile.

  • , program.cpp, a.out
  • a.out , input.txt

, .

:

0

Source: https://habr.com/ru/post/1678136/


All Articles