Last active
February 13, 2025 17:29
-
-
Save FelipeGrijo/f43665eba9e34870dfc0f15f228b0319 to your computer and use it in GitHub Desktop.
readline nodejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://gist.github.com/FelipeGrijo | |
import readline from 'node:readline/promises'; | |
import { stdin, stdout } from 'node:process'; | |
const rl = readline.createInterface({ input: stdin, output: stdout }); | |
const ask = rl.question.bind(rl); | |
// const waitForEnter = async (msg = 'Pressione Enter para continuar...') => await ask(msg); | |
const prompt = async (questions) => { | |
const answers = {}; | |
try { | |
for (const question of questions) { | |
const message = question.message || question; | |
const key = question.key || question.name || 'prompts'; | |
const answer = await ask(message); | |
if (key !== 'prompts') { | |
answers[key] = answer; | |
} else { | |
if (!answers.prompts) { | |
answers.prompts = []; | |
} | |
answers.prompts.push({ question: message, answer }); | |
} | |
} | |
return answers; | |
} catch (error) { | |
console.error(error); | |
} finally { | |
rl.close(); | |
} | |
return answers; | |
}; | |
const questions = [ | |
{ | |
key: 'name', | |
message: 'Qual é o seu nome? ', | |
}, | |
{ | |
key: 'age', | |
message: 'Qual é a sua idade? ', | |
}, | |
]; | |
const questionList = ['Digite seu username:', 'Digite o nome do seu país:']; | |
(async () => { | |
try { | |
const response = await prompt([...questions, ...questionList]); | |
console.log(response); | |
} catch (error) { | |
console.error('Ocorreu um erro:', error); | |
} | |
})(); | |
/* | |
{ | |
name: 'Felipe', | |
age: '00', | |
prompts: [ | |
{ question: 'Digite seu username:', answer: '@FelipeGrijo' }, | |
{ question: 'Digite o nome do seu País:', answer: 'Brasil' } | |
] | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment