出现提示时,节点 JS 生成输入文本

Node JS spawn input text when prompted

我正在使用 Node JS 子进程来 运行 一个命令,我需要以某种方式在出现提示时自动输入一些文本并从我的 stdout 中自动按回车键,不知道如何这样做...

var child = spawn('COMMAND-TO-RUN', {
  shell: true
});

child.stdout.on('data', function (data) {
  // when prompted in the terminal, need to input something automatically from here...
  console.log(data)
  console.log("STDOUT:", data.toString());
});

更新

我已经尝试使用 child.stdin.write,但在终端提示输入 SSH 密码的问题中这不起作用,因为我正在尝试自动将密码输入到通过 JS 终端,不知道为什么这不起作用。

您可以将子进程的标准输入和标准错误通过管道传递给父进程。例如:

var child = spawn('ps', {
    shell: true
});

child.stdout.on('data', function (data) {
    // when prompted in the terminal, need to input something automatically from here...
    process.stdout.write('Something I want to print\n\n');
    console.log(data)
    console.log("STDOUT:", data.toString());
});