如何在nodejs控制台中隐藏密码?

时间:2014-06-04 12:33:11

标签: javascript node.js

我想隐藏密码输入。我在stackoverflow中看到很多答案但是如果我按退格键我无法验证值。条件返回false。

我尝试了几种解决方案来覆盖这个功能但是如果按下退格键我遇到了缓冲区的问题,我得到了隐形字符\b

我按下:“A”,退格键,“B”,我在缓冲区中有这个:“\ u0041 \ u0008 \ u0042”(toString()='A \ bB')而不是“B”。

我有:

var readline = require('readline');

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

rl.question("password : ", function(password) {
    console.log("Your password : " + password);
});

10 个答案:

答案 0 :(得分:33)

这可以通过读取线来处理,通过静音流拦截输出,就像在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;

答案 1 :(得分:22)

覆盖应用程序的readline界面的_writeToOutput:https://github.com/nodejs/node/blob/v9.5.0/lib/readline.js#L291

要隐藏密码输入,您可以使用:

第一个解决方案:"密码:[= - ]"

当你按下触摸时,此解决方案有动画:

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

代码:

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);
};

此序列" \ x1B [2K \ x1BD"使用两个转义序列:

  • Esc [2K:清除整行。
  • Esc D:移动/滚动窗口一行。

要了解详情,请阅读:http://ascii-table.com/ansi-escape-sequences-vt-100.php

第二个解决方案:"密码:****"

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);
};

您可以使用以下内容清除历史记录:

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

答案 2 :(得分:7)

您可以使用readline-sync模块而不是节点readline

密码隐藏功能是通过它内置的" hideEchoBack"选项。

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

答案 3 :(得分:3)

想要加入标记的解决方案#2。

当我们检测到行尾时,我相信我们应该删除事件处理程序而不仅仅是stdin.pause()。如果您在其他地方等待rl.question / rl.prompt,这可能是一个问题。 在这些情况下,如果使用stdin.pause(),它只会退出程序而不会出现任何错误,并且调试非常烦人。

function hidden(query, callback) {
    var stdin = process.openStdin();
    var onDataHandler = function(char) {
        char = char + "";
        switch (char) {
          case "\n": case "\r": case "\u0004":
            // Remove this handler
            stdin.removeListener("data",onDataHandler); 
            break;//stdin.pause(); break;
          default:
            process.stdout.write("\033[2K\033[200D" + query + Array(rl.line.length+1).join("*"));
          break;
        }
    }
    process.stdin.on("data", onDataHandler);

    rl.question(query, function(value) {
      rl.history = rl.history.slice(1);
      callback(value);
    });
}

答案 4 :(得分:3)

我的解决方案,在网上从各个位拼凑而成:

import readline from 'readline';

export const hiddenQuestion = query => new Promise((resolve, reject) => {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  const stdin = process.openStdin();
  process.stdin.on('data', char => {
    char = char + '';
    switch (char) {
      case '\n':
      case '\r':
      case '\u0004':
        stdin.pause();
        break;
      default:
        process.stdout.clearLine();
        readline.cursorTo(process.stdout, 0);
        process.stdout.write(query + Array(rl.line.length + 1).join('*'));
        break;
    }
  });
  rl.question(query, value => {
    rl.history = rl.history.slice(1);
    resolve(value);
  });
});

用法是这样的:

// import { hiddenQuestion } from './hidden-question.js';

const main = async () => {
  console.log('Enter your password and I will tell you your password! ');
  const password = await hiddenQuestion('> ');
  console.log('Your password is "' + password + '". ');
};

main().catch(error => console.error(error));

答案 5 :(得分:1)

也可以使用tty.ReadStream
更改process.stdin的模式 禁用回显输入字符。

let read_Line_Str = "";
let credentials_Obj = {};
process.stdin.setEncoding('utf8');
process.stdin.setRawMode( true );
process.stdout.write( "Enter password:" ); 
process.stdin.on( 'readable', () => {
  const chunk = process.stdin.read();
  if ( chunk !== null ) {
    read_Line_Str += chunk;
    if( 
      chunk == "\n" ||
      chunk == "\r" ||
      chunk == "\u0004"
    ){
      process.stdout.write( "\n" );
      process.stdin.setRawMode( false );
      process.stdin.emit('end'); /// <- this invokes on.end
    }else{
      // providing visual feedback
      process.stdout.write( "*" );  
    }  
  }else{
    //console.log( "readable data chunk is null|empty" );
  }
} );
process.stdin.on( 'end', () => {
  credentials_Obj.user = process.env.USER;
  credentials_Obj.host = 'localhost';
  credentials_Obj.database = process.env.USER;
  credentials_Obj.password = read_Line_Str.trim();
  credentials_Obj.port = 5432;
  //
  connect_To_DB( credentials_Obj );
} );

答案 6 :(得分:1)

使用readline的另一种方法:

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

rl.input.on("keypress", function (c, k) {
  // get the number of characters entered so far:
  var len = rl.line.length;
  // move cursor back to the beginning of the input:
  readline.moveCursor(rl.output, -len, 0);
  // clear everything to the right of the cursor:
  readline.clearLine(rl.output, 1);
  // replace the original input with asterisks:
  for (var i = 0; i < len; i++) {
    rl.output.write("*");
  }
});

rl.question("Enter your password: ", function (pw) {
  // pw == the user's input:
  console.log(pw);
  rl.close();
});

答案 7 :(得分:0)

您可以按照建议的prompt使用here模块。

const prompt = require('prompt');

const properties = [
    {
        name: 'username', 
        validator: /^[a-zA-Z\s\-]+$/,
        warning: 'Username must be only letters, spaces, or dashes'
    },
    {
        name: 'password',
        hidden: true
    }
];

prompt.start();

prompt.get(properties, function (err, result) {
    if (err) { return onErr(err); }
    console.log('Command-line input received:');
    console.log('  Username: ' + result.username);
    console.log('  Password: ' + result.password);
});

function onErr(err) {
    console.log(err);
    return 1;
}

答案 8 :(得分:0)

这是我的解决方案,它不需要任何外部库(除了 readline)或大量代码。

// turns off echo, but also doesn't process backspaces
// also captures ctrl+c, ctrl+d
process.stdin.setRawMode(true); 

const rl = require('readline').createInterface({input: process.stdin});
rl.on('close', function() { process.exit(0); }); // on ctrl+c, doesn't work? :(
rl.on('line', function(line) {
    if (/\u0003\.test(line)/) process.exit(0); // on ctrl+c, but after return :(
    // process backspaces
    while (/\u007f/.test(line)) {
        line = line.replace(/[^\u007f]\u007f/, '').replace(/^\u007f+/, '');
    }

    // do whatever with line
});

答案 9 :(得分:0)

承诺的打字稿原生版本:

这也将处理多个 question 调用(正如@jeffrey-woo 指出的那样)。我选择不使用 * 替换输入,因为它感觉不是很 unix-y,而且我发现有时如果输入太快,它会出现故障。

import readline from 'readline';

export const question = (question: string, options: { hidden?: boolean } = {}) =>
  new Promise<string>((resolve, reject) => {
    const input = process.stdin;
    const output = process.stdout;

    type Rl = readline.Interface & { history: string[] };
    const rl = readline.createInterface({ input, output }) as Rl;

    if (options.hidden) {
      const onDataHandler = (charBuff: Buffer) => {
        const char = charBuff + '';
        switch (char) {
          case '\n':
          case '\r':
          case '\u0004':
            input.removeListener('data', onDataHandler);
            break;
          default:
            output.clearLine(0);
            readline.cursorTo(output, 0);
            output.write(question);
            break;
        }
      };
      input.on('data', onDataHandler);
    }

    rl.question(question, (answer) => {
      if (options.hidden) rl.history = rl.history.slice(1);
      rl.close();
      resolve(answer);
    });
  });

用法:

(async () => {
  const hiddenValue = await question('This will be hidden', { hidden: true });
  const visibleValue = await question('This will be visible');
  console.log('hidden value', hiddenValue);
  console.log('visible value', visibleValue);
});