考虑以下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'
}