Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send user input from NodeJS to shell script

I have this NodeJS script:

var util  = require('util'),
process = require('child_process'),
ls    = process.exec('test.sh');

ls.stdout.on('data', function (data) {
   console.log(data.toString());
   ls.stdin.write('Test');
});

and this shell script:

#!/bin/bash
echo "Please input your name:";
read name;                 
echo "Your name is $name";

I tried to run the NodeJS script and it stucked at "Please input your name:". Does anyone know how to send an input from NodeJS script to the shell script ?

Thanks

like image 221
Rudy Lee Avatar asked Dec 03 '25 01:12

Rudy Lee


2 Answers

You will have to say something like this:

ls.stdin.write('test\n');

OR

you can inherit standard streams if you want input from user using spawn.

like this:

var spawn = require('child_process').spawn;
spawn('sh',['test.sh'], { stdio: 'inherit' });
like image 89
Mritunjay Avatar answered Dec 05 '25 14:12

Mritunjay


Did you try adding '\n' to the end of your input (e.g. ls.stdin.write('Test\n');) to simulate pressing return/enter?

Also, you want process.spawn, not process.exec. The latter does not have a streaming interface like you are using, but it instead executes the command and buffers stdout and stderr output (passing it to the callback given to process.exec()).

like image 21
mscdex Avatar answered Dec 05 '25 14:12

mscdex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!