Read a password without echoing it
Prompt for a password in a Node.js 24 CLI without echoing it by putting stdin in raw mode and handling Enter, Backspace and Ctrl+C yourself.
readline.question prints every key the user types, which is wrong for a password. Raw mode hands you the keys one at a time and prints nothing, so you decide what appears.
function askHidden(prompt) {
return new Promise((resolve, reject) => {
const { stdin, stdout } = process;
if (!stdin.isTTY) return reject(new Error('stdin is not a terminal'));
stdout.write(prompt);
stdin.setRawMode(true);
stdin.setEncoding('utf8');
let value = '';
const onData = (chunk) => {
for (const ch of chunk) {
if (ch === '\r' || ch === '\n') {
stdin.setRawMode(false);
stdin.off('data', onData);
stdin.pause();
stdout.write('\n');
return resolve(value);
}
if (ch === '\u0003') { stdin.setRawMode(false); process.exit(130); }
if (ch === '\u007f') value = value.slice(0, -1);
else value += ch;
}
};
stdin.on('data', onData);
stdin.resume();
});
}
const password = await askHidden('Password: ');
console.log(`got ${password.length} characters`);Password:
got 12 characterssetRawMode(true) turns off the terminal's own line editing and echo, so each key arrives as it is pressed and nothing is printed back. That means the code must handle the special keys: Enter finishes, Backspace removes the last character, and Ctrl+C, which no longer sends SIGINT in raw mode, exits with the usual code 130. See readStream.setRawMode.
Raw mode exists only when stdin is a terminal, so piped input such as a CI secret needs a separate path, an environment variable or a file. Always switch raw mode off before you return, or the shell is left unusable. The password is a plain string in memory, so do not log it.