I'm trying to create a simple node API that would spawn a shell script and add user input from a POST call to that spawn. I created a controller called testController.js that would run a script called test.sh located in the same project
I was having a few problems writing the user input but thankfully this solution saved me.
So this really simple controller function ended up to be:
testController.js:
exports.create_task = function (req, res) {
var spawn = require("child_process").spawn;
var spawned = spawn("sh", ["/var/www/html/node_test_proj/test.sh"]);
spawned.stdout.on("data", function (data) {
console.log("In stdout");
spawned.stdin.write(req.body.name + "\n");
spawned.stdin.write(req.body.number + "\n");
});
res.send("posted");
};
My shell script would basically just take a name and number and export those details into a file:
test.sh:
#!/bin/bash
echo "Please input your name"
read name
echo "Please input your number"
read number
echo "Your name is $name and number $number" > knowingthis.txt;
Simple enough; does what it's supposed to and (given name abc and number 123) prints out:
your name is abc and number 123
However, to simplify things further I decide to replace the unnecessary echo statements with something simpler i.e read -p. Now my modified script becomes:
#!/bin/bash
read -p "Please input your name: " name;
read -p "Please input your number: " number;
echo "Your name is $name and number $number" > knowingthis.txt;
Lo and behold! Now when I spawn the script it no longer works; it doesn't even log the "In stdout" so that means that it's never really going in that clause, it simply exports the file with variables empty in the sentence, leaving the output to be:
your name is and number
I thought maybe there's something wrong with the script, so I ran it directly, but it was working fine. Why is it working with read and not read -p? Is there something I need to change in my function? Is it not a normal stdout stream but something else?