refactor(install.js): 优化密码输入处理逻辑
This commit is contained in:
+24
-28
@@ -205,6 +205,7 @@ function askPassword(question) {
|
|||||||
|
|
||||||
let password = '';
|
let password = '';
|
||||||
const stdin = process.stdin;
|
const stdin = process.stdin;
|
||||||
|
const stdout = process.stdout;
|
||||||
|
|
||||||
const cleanup = () => {
|
const cleanup = () => {
|
||||||
if (stdin.isTTY) {
|
if (stdin.isTTY) {
|
||||||
@@ -216,41 +217,36 @@ function askPassword(question) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const onData = (char) => {
|
const onData = (char) => {
|
||||||
const c = char;
|
const code = char.charCodeAt(0);
|
||||||
|
|
||||||
switch (c) {
|
if (code === 10 || code === 13) {
|
||||||
case '\n':
|
cleanup();
|
||||||
case '\r':
|
stdout.write('\n');
|
||||||
case '\u0004':
|
resolve(password);
|
||||||
cleanup();
|
} else if (code === 3) {
|
||||||
console.log();
|
cleanup();
|
||||||
resolve(password);
|
stdout.write('\n已取消\n');
|
||||||
break;
|
process.exit(0);
|
||||||
case '\u0003':
|
} else if (code === 127 || code === 8) {
|
||||||
cleanup();
|
if (password.length > 0) {
|
||||||
console.log('\n已取消');
|
password = password.slice(0, -1);
|
||||||
process.exit(0);
|
stdout.write('\b \b');
|
||||||
break;
|
}
|
||||||
case '\u007F':
|
} else if (code >= 32) {
|
||||||
case '\b':
|
password += char;
|
||||||
if (password.length > 0) {
|
stdout.write('*');
|
||||||
password = password.slice(0, -1);
|
|
||||||
process.stdout.write('\b \b');
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
password += c;
|
|
||||||
process.stdout.write('*');
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
if (stdin.isTTY) {
|
if (stdin.isTTY) {
|
||||||
stdin.setRawMode(true);
|
stdin.setRawMode(true);
|
||||||
|
stdin.resume();
|
||||||
|
stdin.on('data', onData);
|
||||||
|
} else {
|
||||||
|
rl.question('', (answer) => {
|
||||||
|
resolve(answer.trim());
|
||||||
|
});
|
||||||
}
|
}
|
||||||
stdin.setEncoding('utf8');
|
|
||||||
stdin.on('data', onData);
|
|
||||||
stdin.resume();
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user