如何在nodejs控制台中隐藏密码? [英] How to hide password in the nodejs console?

查看:293
本文介绍了如何在nodejs控制台中隐藏密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to hide password input. I see many answers in stackoverflow but I can't verify value if I press backspace. The condition return false.

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

I tried several solution to overwrite the function but I got an issue with buffer if I press backspace, I got invisible character \b.

我按下:A,退格,B,我在我的缓冲区中:\ u0041 \ u0008 \ u0042(toString()='A \\\ BB')而不是B。

I press : "A", backspace, "B", I have in my buffer this : "\u0041\u0008\u0042" (toString() = 'A\bB') and not "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);
});


推荐答案

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

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 :

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

This solution has animation when you press a touch :

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使用两个转义序列:

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


  • Esc [2K:清除整行。

  • Esc D:向上移动/滚动窗口一行。

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

到了解更多信息,请阅读: http://ascii-table.com/ansi -escape-sequences-vt-100.php

To learn more, read this : 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);
};



您可以通过以下方式清除历史记录:



You can clear history with :

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

这篇关于如何在nodejs控制台中隐藏密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆