forked from handshake-org/hs-airdrop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadline.js
96 lines (74 loc) · 1.89 KB
/
readline.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'use strict';
/* eslint no-use-before-define: "off" */
const assert = require('bsert');
const {StringDecoder} = require('string_decoder');
async function readLine(prefix = '', secret = false) {
assert(typeof prefix === 'string');
assert(typeof secret === 'boolean');
const {stdin, stdout} = process;
const decoder = new StringDecoder('utf8');
let out = '';
stdin.setRawMode(true);
stdin.resume();
if (prefix)
stdout.write(`${prefix}: `);
return new Promise((resolve, reject) => {
const cleanup = () => {
stdin.removeListener('error', onError);
stdin.removeListener('data', onData);
stdin.pause();
stdin.setRawMode(false);
};
const onError = (err) => {
cleanup();
reject(err);
};
const onData = (data) => {
if (data.length === 0)
return;
switch (data[0]) {
case 0x5c: { // ^\
process.exit(1);
break;
}
case 0x03: // ^C
case 0x04: // ^D
case 0x0d: { // <CR>
cleanup();
stdout.write('\n');
resolve(out);
break;
}
case 0x7f: { // Backspace
if (out.length > 0) {
if (!secret)
stdout.write('\x1b[D \x1b[D');
out = out.slice(0, -1);
}
break;
}
case 0x1b: { // Escape code
break;
}
default: {
const str = decoder.write(data);
if (!secret)
stdout.write(str, 'utf8');
out += str;
if (out.length > 4096) {
cleanup();
reject(new Error('String too long.'));
}
break;
}
}
};
stdin.on('error', onError);
stdin.on('data', onData);
});
}
async function readPassphrase() {
return readLine('Passphrase', true);
}
exports.readLine = readLine;
exports.readPassphrase = readPassphrase;