Прочитайте вопрос из stdout и напишите ответ на stdin - PullRequest
0 голосов
/ 07 ноября 2018

Рассмотрим скрипт 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'
}
...