子进程输出中不显示提示信息

问题描述 投票:0回答:0

我正在运行一个 Node.js 脚本,该脚本使用 child_process 模块中的 spawn 函数创建一个子进程。子进程运行 zsh shell 并提示用户使用 read 命令输入名称。但是,我在子进程的输出中看不到提示信息

这是我的代码:

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

let child;

async function executeCommandOrSendInput(commandOrInput) {
  if (!child || child.exitCode !== null) {
    console.log('Creating new child process');
    child = spawn('zsh', [], { stdio: 'pipe' });

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

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

    child.on('close', (code) => {
      console.log(`Child process exited with code ${code}`);
    });
  }

  console.log('Sending command or input:', commandOrInput);
  child.stdin.write(commandOrInput + '\n');
}

(async () => {
  try {
    await executeCommandOrSendInput('read "name?name?" ;echo $name > /tmp/thename.txt; echo done');
    await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for 1 second
    await executeCommandOrSendInput('my_name');
    await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for 1 second
    child.stdin.end(); // End the child process
  } catch (error) {
    console.error('An error occurred:', error);
  }
})();

输出为

Creating new child process
Sending command or input: read "name?name?" ;echo $name > /tmp/thename.txt; echo done
Sending command or input: my_name
Output: done

Child process exited with code 0

我正在使用一个奇怪的 zsh 版本的 read 显然把消息放在 ? 之前。

当我运行脚本时,我希望看到名字?子进程输出中的提示消息,但它不存在。怎么才能看到呢?

我在 tmp 目录中创建的文件确实有正确的输出

node.js zsh prompt child-process spawn
© www.soinside.com 2019 - 2024. All rights reserved.