-
-
Notifications
You must be signed in to change notification settings - Fork 14
3. Recipes
Jared Van Valkengoed edited this page Aug 6, 2024
·
5 revisions
When asking many questions, you might not want to keep one variable per answer everywhere.
In which case, you can put the answer inside an object.
const answers = {
firstName: await term.input("What's your first name?"),
allowEmail: await term.input('Do you allow us to send you email?'),
};
console.log(answers.firstName);
Maybe some questions depend on some other question's answer.
const allowEmail = await term.input("Can I have your email, if so say 'yes'")
let email;
if (allowEmail === 'yes') {
email = await term.input('What is your email address');
}
Handle multiple questions sequentially using Promises.
const getAnswers = async () => {
const firstName = await term.input("What's your first name?");
const lastName = await term.input("What's your last name?");
const age = await term.input("What's your age?");
return { firstName, lastName, age };
};
getAnswers().then(answers => console.log(answers));
An example of how you could use Yargs with your project.
async function loadYargs() {
if (typeof window !== "undefined" && window.document) {
// Browser environment
const yargsModule = await import(
"https://esm.sh/[email protected]/browser.mjs"
); // version required for browser.
return yargsModule.default;
} else {
// Node.js environment
const yargs = await import("https://esm.sh/yargs");
return yargs.default;
}
}
const Yargs = await loadYargs();
// initialize your Termino.js instance here etc!
const yargs = Yargs()
.scriptName(">")
.command(
"clear",
"clear the output window",
() => {},
() => {
// ...
}
)
.command(
"alert <message...>",
"display an alert",
() => {},
(argv) => {
alert(argv.message.join(" "));
}
)
.wrap(null)
.strict()
.demandCommand(1)
.version("v1.0.0");
const argv = yargs.parse(await term.input("--help"), (err, argv, output) => {
if (output) {
term.output(output);
}
});