Last active
February 9, 2023 18:20
-
-
Save n8jadams/fe703e0e922d3d3b713ea00e4122f772 to your computer and use it in GitHub Desktop.
Read in non-hidden and hidden inputs in a cli
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
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