Skip to content

Instantly share code, notes, and snippets.

@n8jadams
Last active February 9, 2023 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n8jadams/fe703e0e922d3d3b713ea00e4122f772 to your computer and use it in GitHub Desktop.
Save n8jadams/fe703e0e922d3d3b713ea00e4122f772 to your computer and use it in GitHub Desktop.
Read in non-hidden and hidden inputs in a cli
const readline = require("readline");
const question = (query) =>
new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question(`${query}\n`, (value) => {
rl.close();
resolve(value);
});
});
const hiddenQuestion = (query) =>
new Promise((resolve) => {
console.log(query);
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl._writeToOutput = () => {};
const stdin = process.openStdin();
process.stdin.on("data", (char) => {
char = char.toString("utf-8");
switch (char) {
case "\n":
case "\r":
case "\u0004":
// Finished writing their response
stdin.pause();
break;
// You might make this case optional, (Ctrl-C)
case "\u0003":
// Ctrl-C
process.exit(0);
default:
process.stdout.clearLine();
readline.cursorTo(process.stdout, 0);
break;
}
});
rl.question("", (value) => {
rl.history = rl.history.slice(1);
rl.close();
resolve(value);
});
});
async function main() {
const username = await question("What is your username?");
const password = await hiddenQuestion("What is your password?");
console.log({ username, password });
}
void main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment