How to hide password in the nodejs console?

This can be handled with readline by intercepting the output through a muted stream, as is done in the read project on npm (https://github.com/isaacs/read/blob/master/lib/read.js):

var readline = require('readline');
var Writable = require('stream').Writable;

var mutableStdout = new Writable({
  write: function(chunk, encoding, callback) {
    if (!this.muted)
      process.stdout.write(chunk, encoding);
    callback();
  }
});

mutableStdout.muted = false;

var rl = readline.createInterface({
  input: process.stdin,
  output: mutableStdout,
  terminal: true
});

rl.question('Password: ', function(password) {
  console.log('\nPassword is ' + password);
  rl.close();
});

mutableStdout.muted = true;

Overwrite _writeToOutput of application's readline interface : https://github.com/nodejs/node/blob/v9.5.0/lib/readline.js#L291

To hide your password input, you can use :

FIRST SOLUTION : "password : [=-]"

This solution has animation when you press a touch :

password : [-=]
password : [=-]

The code :

var readline = require('readline');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.stdoutMuted = true;

rl.query = "Password : ";
rl.question(rl.query, function(password) {
  console.log('\nPassword is ' + password);
  rl.close();
});

rl._writeToOutput = function _writeToOutput(stringToWrite) {
  if (rl.stdoutMuted)
    rl.output.write("\x1B[2K\x1B[200D"+rl.query+"["+((rl.line.length%2==1)?"=-":"-=")+"]");
  else
    rl.output.write(stringToWrite);
};

This sequence "\x1B[2K\x1BD" uses two escapes sequences :

  • Esc [2K : clear entire line.
  • Esc D : move/scroll window up one line.

To learn more, read this : http://ascii-table.com/ansi-escape-sequences-vt-100.php

SECOND SOLUTION : "password : ****"

var readline = require('readline');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.stdoutMuted = true;

rl.question('Password: ', function(password) {
  console.log('\nPassword is ' + password);
  rl.close();
});

rl._writeToOutput = function _writeToOutput(stringToWrite) {
  if (rl.stdoutMuted)
    rl.output.write("*");
  else
    rl.output.write(stringToWrite);
};

You can clear history with :

rl.history = rl.history.slice(1);

You can use the readline-sync module instead of node's readline.

Password-hiding functionality is built in via it's "hideEchoBack" option.

https://www.npmjs.com/package/readline-sync