响应 child_process spawn nodejs 中的密码查询

J_R*_*ROC 5 spawn child-process node.js ubuntu-16.04

需要帮助弄清楚这一点。

我试图通过子进程 spawn 调用外部应用程序,并在调用该应用程序后要求输入密码。然后我得到一个致命错误并且子进程退出。我已经尝试了几种不同的组合来放置 child.stdin.write('somepassword\n') 但我得到了同样的错误。我认为这与应用程序没有将孩子视为终端有关。

示例代码:

const { spawn } = require('child_process');

const child = spawn('./some-app',[arguments],{shell:true});

// process.stdin.pipe(child.stdin)

child.stdin.write('testpw\n'); // has no effect

child.stdout.on('data', (data) => {
    console.log(`child stdout:\n${data}`);
    //child.stdin.write('testpw\n'); // no effect here either
});

child.stdin.end(); 

child.stderr.on('data', (data) => {
    console.error(`child stderr:\n${data}`);
});

child.on('exit', function (code, signal) {
    console.log('child process exited with ' +
                `code ${code} and signal ${signal}`);
});

Terminal Output

> node spawn.js

child stdout:
Enter password: Fatal error:
  Unix.Unix_error(Unix.ENOTTY, "tcgetattr", "")

child process exited with code 1 and signal null
Run Code Online (Sandbox Code Playgroud)

这个错误让我相信 child_process 看到的环境不是一个 tty,但是搜索如何让孩子以这种方式看到它让我陷入了一个深深的 unix 兔子洞,并且没有在与节点相关的答案中脱颖而出。我在 Ubuntu 16.04 和 nodejs V10.15 上运行它

编辑 如果我更改 child.stdin 的 stdio 流,该进程不再有致命错误,但现在只是坐下来等待用户的键盘输入。但是写入 process.stdin.write() 将显示在屏幕上,但除非我在键盘上实际输入,否则孩子不会响应。

const { spawn } = require('child_process');

const child = spawn('./some-app',
                    [arguments],
                    {
                     shell:true,
                     stdio:['inherit','pipe','pipe']
                    });


child.stdout.on('data', (data) => {
    console.log(`child stdout:\n${data}`);
    process.stdin.write('testpw\n'); // displays but not handled by the 
                                     // process
}); 

child.stderr.on('data', (data) => {
    console.error(`child stderr:\n${data}`);
});

child.on('exit', function (code, signal) {
    console.log('child process exited with ' +
                `code ${code} and signal ${signal}`);
});

Terminal Output

> node spawn.js

child stdout:
Enter password:
testpw         <-- process sits here waiting for real keyboard input
Run Code Online (Sandbox Code Playgroud)