如何使用node的child_process库在Mac上启动交互式终端窗口?

时间:2019-07-22 20:25:40

标签: node.js bash typescript .net-core child-process

我想通过dotnet dev-certs https --trust库在交互式终端中执行bash命令-child_process。 因为它要求输入用户密码,所以它必须是交互式终端。

我已经尝试过使用AppleScript,但是用户体验却很差,因为它倾向于留下半封闭的终端窗口。

编辑-添加了我用来创建child_process的代码段。

import * as cp from 'child_process'
cp.spawn('dotnet dev-certs https --trust', {})

我尝试了cp.spawncp.exec的许多组合。 例如cp.spawn('...', { shell: true, stdio: 'ignore', detached: true })

cp.spawn实际上创建了一个进程,但是它不是交互式的,并且会立即终止。

1 个答案:

答案 0 :(得分:0)

首先,您必须使用 stdout.on('data',data => {})过滤来自stdout的传入数据,以找到用户输入的shell请求。找到特定的行之后,您只需通过 stdin.write('any input \ n')

将数据发送到Shell
import * as cp from 'child_process'
const ls = cp.spawn('dotnet dev-certs https --trust', {})

    ls.stdout.on('data', function (data) {
       const currentData = data.toString();

       //check for password input notification:
       if(currentData === "input credentials: ")
       {
         //send the password via stdin. \n does the trick over here. 
         ls.stdin.write('Password\n');
       }  
    });