Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get password from input using node.js

Tags:

node.js

input

How to get password from input using node.js? Which means you should not output password entered in console.

like image 889
Alfred Avatar asked Jan 16 '11 23:01

Alfred


2 Answers

You can use the read module (disclosure: written by me) for this:

In your shell:

npm install read

Then in your JS:

var read = require('read')
read({ prompt: 'Password: ', silent: true }, function(er, password) {
  console.log('Your password is: %s', password)
})
like image 132
isaacs Avatar answered Sep 24 '22 08:09

isaacs


Update 2015 Dec 13: readline has replaced process.stdin and node_stdio was removed from Node 0.5.10.

var BACKSPACE = String.fromCharCode(127);


// Probably should use readline
// https://nodejs.org/api/readline.html
function getPassword(prompt, callback) {
    if (prompt) {
      process.stdout.write(prompt);
    }

    var stdin = process.stdin;
    stdin.resume();
    stdin.setRawMode(true);
    stdin.resume();
    stdin.setEncoding('utf8');

    var password = '';
    stdin.on('data', function (ch) {
        ch = ch.toString('utf8');

        switch (ch) {
        case "\n":
        case "\r":
        case "\u0004":
            // They've finished typing their password
            process.stdout.write('\n');
            stdin.setRawMode(false);
            stdin.pause();
            callback(false, password);
            break;
        case "\u0003":
            // Ctrl-C
            callback(true);
            break;
        case BACKSPACE:
            password = password.slice(0, password.length - 1);
            process.stdout.clearLine();
            process.stdout.cursorTo(0);
            process.stdout.write(prompt);
            process.stdout.write(password.split('').map(function () {
              return '*';
            }).join(''));
            break;
        default:
            // More passsword characters
            process.stdout.write('*');
            password += ch;
            break;
        }
    });
}

getPassword('Password: ', (ok, password) => { console.log([ok, password]) } );
like image 34
mikemaccana Avatar answered Sep 24 '22 08:09

mikemaccana