首页 > 解决方案 > 从标准输出读取一个问题并将响应写入标准输入

问题描述

考虑这个 bash 脚本:

# script-with-input.sh
# can't change this file :(
echo Hi
read -p "what's your name: " name
echo "That's a nice name."
read -p "what's you job: " job
echo Hello, $job $name!

我如何使用这些问题与它交流child_process.spawn并对问题做出有意义的回答?我需要在给出回复之前得到一个问题(不能仅根据订单做出我的回复),但我的应用程序只是挂起等待输入,并且在stdout. 我知道这与stdout行缓冲有关,但不知道如何解决。

const child_process = require('child_process')
const cmd = 'sh script-with-input.sh'
const child = child_process.spawn(cmd, [], {shell: true})
child.stdout.on('data', data => {
  console.log('data:', data.toString())
})
//child.stdin.write('John\n\metalworker\n')
function getResponse(question) { //...how do I get the question?
  return question.includes('name') ? 'John' : 'metalworker'
}

标签: node.jsstdoutstdinchild-processspawn

解决方案


推荐阅读