0

JS:

#!/usr/bin/env node
const util = require("util"),
    inquirer = require("inquirer")
function promptUser() {
    inquirer.prompt([
        {
            type: "list",
            name: "scheme",
            message: "How would you like to build",
            choices: [
                {
                    name: "build develop",
                    value: "develop"
                }, {
                    name: "build product",
                    value: "product"
                }
            ]
        }
    ], earlyAnswers => {
        console.log(earlyAnswers.scheme);
    });
}
promptUser();

it will ask a question and I can select a answer, log answer, like:

enter image description hereenter image description here

I want to exec this js in shell:

#!/bin/sh
echo 123
a=`node ./test2.js`

let a = answer, but can't exec like:

enter image description here

how do I exec this JS?

1 Answer 1

1

Your javascript is actually running, but your backticks in the command

a=`node ./test2.js`

cause the shell to capture standard out and assign it to the variable a. All of stdout is captured, not just the last line, so nothing is presented to the user.

One possible way to solve this is to use the node.js process's exit code. Here is a generic script that will accept the prompt an options on the command line, and set its exit code to the zero-based index of the selection.

#! /usr/bin/env node --harmony_destructuring
util = require("util");
inquirer = require("inquirer");

var [program, file, textprompt, ...args] = process.argv

var choices = [];
args.forEach(function(E) {
    var [name, value] = E.split(":",2);
    choices.push({name: name, value: value});
});

function promptUser() {
    inquirer.prompt([
        {
            type: "list",
            name: "scheme",
            message: textprompt,
            choices: choices
        }
    ]).then(function(answer) {
        if (answer && answer.scheme) {
            position = choices.findIndex(function(E) { return E.value == answer.scheme; });
            process.exit(position);
        } else {
            process.exit(-1);
        }
    })
}
if (choices.length > 0)
    promptUser();

Which could be used like this:

#! /bin/bash
./test2.js "How would you like to build?" "build develop:develop" "build product:product"
selected=$?
case $selected in
    0) echo "Selected develop";; 
    1) echo "Selected product";;
    *) echo "Invalid selection";;
esac
Sign up to request clarification or add additional context in comments.

Comments

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.