Created
March 23, 2015 08:57
-
-
Save ValeriiVasin/68545ac47afe77cfaaec to your computer and use it in GitHub Desktop.
Reading password node.js
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
// Get a password from the console | |
function getPassword(done) { | |
process.stdin.resume(); | |
process.stdin.setEncoding('utf8'); | |
process.stdin.setRawMode(true); | |
var password = ''; | |
process.stdout.write('Password: '); | |
process.stdin.on('data', function(ch) { | |
ch = ch + ''; | |
// backspace | |
if (ch.charCodeAt(0) === 127) { | |
password = password.slice(0, -1); | |
return; | |
} | |
switch (ch) { | |
case '\n': | |
case '\r': | |
case '\u0004': | |
// They've finished typing their password | |
process.stdin.setRawMode(false); | |
process.stdin.pause(); | |
process.stdout.write('\n'); | |
done(password); | |
break; | |
case '\u0003': | |
// Ctrl C | |
throw new Error('Cancelled'); | |
default: | |
// More passsword characters | |
password += ch; | |
break; | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment