1

i'm calling an async nodejs function that uses prompts(https://www.npmjs.com/package/prompts) basically, the user is presented options and after they select one, i want the selection outputted to a variable in bash. I cannot get this to work. it either hangs, or outputs everything since prompts is a user interface that uses stdout

//nodefunc.js

async run() {
  await blahhhh;
  return result; // text string
}

console.log(run());

// bash

x=$(node nodefunc.js)

echo $x 


3
  • What is output of node nodefunc.js and what you want in variable in X Commented Aug 31, 2020 at 4:26
  • The output will be a string, that I want stored in x. Commented Aug 31, 2020 at 4:41
  • try executing code in verbose mode. tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html Commented Aug 31, 2020 at 4:49

1 Answer 1

1

Unless you can ensure nothing else in the node script will print to stdout, you will need a different approach.

I'd suggest having the node script write to a temporary file, and have the bash script read the output from there. Something like this perhaps:

const fs = require('fs');
const outputString = 'I am output';
fs.writeFileSync('/tmp/node_output.txt', outputString);
node nodefunc.js

# Assuming the node script ran succesfully, read the output file
x=$(</tmp/node_output.txt)
echo "$x"

# Optionally, cleanup the tmp file
rm /tmp/node_output.txt
Sign up to request clarification or add additional context in comments.

1 Comment

Am I wrong or is everything here happening synchronously? The question was about returning a value from an async nodejs function and echoing that in bash, no?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.