0

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'
}
grabantot
  • 2,111
  • 20
  • 31
  • Sounds like you want to use the [`readline`](https://nodejs.org/api/readline.html) module from the standard library. – Sven Nov 07 '18 at 15:28
  • @Sven Don't see how I can use it. It would've been useful as a replacement for the bash script. But there is no problem with the bash script, it does the job of asking questions just fine. I can't edit it anyway. The problem is that I am unable to read the questions properly. – grabantot Nov 07 '18 at 15:47
  • similar question: https://stackoverflow.com/questions/15339379/node-js-spawning-a-child-process-interactively-with-separate-stdout-and-stderr-s – grabantot Nov 07 '18 at 16:52
  • one solution I found is `pty.js` npm module, still looking for a better alternative... – grabantot Nov 07 '18 at 17:54

0 Answers0