Created
December 21, 2024 22:50
-
-
Save ryanramage/18f77edf85564bdb972378b5994aaa0e to your computer and use it in GitHub Desktop.
Bare Password entry
This file contains 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
import { ReadStream, WriteStream } from 'bare-tty' | |
import process from 'bare-process' | |
async function promptPassword(promptText) { | |
const input = new ReadStream(process.stdin.fd); | |
const output = new WriteStream(process.stdout.fd); | |
input.setRawMode(true); // Enable raw mode to capture input without echoing | |
try { | |
output.write(promptText); // Display the prompt | |
let password = ''; | |
while (true) { | |
const buffer = Buffer.alloc(1); | |
const bytesRead = await input.read(buffer, 0, 1); // Read one byte at a time | |
if (bytesRead > 0) { | |
const char = buffer.toString('utf8'); | |
if (char === '\r' || char === '\n') { // Enter key | |
output.write('\n'); | |
break; | |
} else if (char === '\u0003') { // Ctrl+C | |
output.write('\n'); | |
process.exit(1); // Exit the process | |
} else if (char === '\b' || char === '\x7f') { // Backspace | |
if (password.length > 0) { | |
password = password.slice(0, -1); | |
output.write('\b \b'); // Handle terminal backspace visually | |
} | |
} else { | |
password += char; // Append character to password | |
} | |
} | |
} | |
return password; | |
} finally { | |
input.setRawMode(false); // Restore terminal mode | |
input.destroy(); | |
} | |
} | |
// Usage example | |
(async () => { | |
try { | |
const password = await promptPassword('Enter your password: '); | |
console.log('Password entered:', password); // Remove in production | |
} catch (err) { | |
console.error(err.message); | |
} | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
run with
npm i bare-tty
npm i bare-process
bare index.mjs