Node Js Terminal Password Input


  const getPassword = (question = "Enter your Password:") => {
    let pass = "";
    process.stdout.write(question);
    return new Promise((reslove, reject) => {
      // Setup raw terminal input
      process.stdin.setRawMode(true);
      process.stdin.setEncoding('utf8');
      process.stdin.resume();

      process.stdin.on('data', (e) => {
        if (e == "\u0003") {
          process.exit(0)
        }

        if (e.startsWith('\u001b')) return;
        else if (e == "\r") {
          console.log("");
          process.stdin.setRawMode(false);
          process.stdin.pause();
          reslove(pass)
          return
        }

        else if (e == "\b") {
          pass = pass.slice(0, -1)
        }
        else {
          pass += e;
        }


        process.stdout.clearLine(0);
        process.stdout.write(`\r${question} ${"*".repeat(pass.length)}`)
        // process.stdout.write("\r" + JSON.stringify(e))
      });
    })
  }

  async function main(params) {
    let pass = await getPassword()
    console.log(pass)
  }

  main()

Comments

Popular posts from this blog

Ensuring File Creation in the Current Directory when Converting Python (.py) Script to Executable (.exe).

Express Production Setup - 4 | HELMET

Node Js Private Key And Public Key Encryption and Decryption