nodejs 控制台输入问题

2020-12-09 11:03:56 +08:00
 zxCoder

想实现一个输入密码控制台不显示的功能,奇怪的问题是,在退格键那部分,当我控制台使用 backspace 退格键删除时,charCodeAt 的值居然是 127,一开始写的 8 一直出错,这是为何,因为 toString()的原因吗

const stdout = process.stdout
const stdin = process.stdin
stdout.write("password:")
stdin.setRawMode(true)
stdin.resume()
let input = ''
const pn = (data) => {
    const c = data.toString()
    switch (c) {
        case '\u0004': // Ctrl-d
        case '\r':
        case '\n':
            return enter()
        case '\u0003': // Ctrl-c
            return ctrlc()
        default:
            // backspace
            if (c.charCodeAt(0) === 127){
                return backspace()
            }
            else{
                return newchar(c)
            }
    }
}
stdin.on("data", pn);
function enter() {
    stdin.removeListener('data', pn)
    console.log("\nYour password is: " + input)
    stdin.setRawMode(false)
    stdin.pause()
}
function ctrlc() {
    stdin.removeListener('data', pn)
    stdin.setRawMode(false)
    stdin.pause()
}
function newchar(c) {
    input += c
    stdout.write("*")
}
function backspace() {
    input = input.slice(0, input.length - 1)
}

668 次点击
所在节点    问与答
6 条回复
ysc3839
2020-12-09 13:09:09 +08:00
zxCoder
2020-12-09 13:46:21 +08:00
ysc3839
2020-12-09 13:47:59 +08:00
@zxCoder 你想表达什么?
zxCoder
2020-12-09 13:58:30 +08:00
@ysc3839 没看懂你发的啥啊 这跟我的问题没关系吧
ysc3839
2020-12-09 14:00:58 +08:00
@zxCoder 怎么没关系?这个就是关于隐藏输入密码的呀。
zxCoder
2020-12-09 14:04:11 +08:00
@ysc3839 我问的是退格键的 unicode 码怎么变成 127.。。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/733657

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX