Consider this bash script:
# 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!
How do I communicate with it using child_process.spawn
and give meaningful responses to the questions?
I need to get a question before giving a response (can't base my responses just on order), but my app just hangs awaiting for input and there is no question on stdout
.
I know this is related to stdout
being line buffered but don't know how to solve it.
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'
}