blob: e1101d81d4c526b950900292257a0f5da885e9b8 (
plain)
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
|
module.exports = {};
let inputBuffer = "";
let initialised = false, haveEOF = false;
let waitQueue = [];
function stdinDataListener(data) {
data = data.toString();
inputBuffer += data;
if (waitQueue.length == 0) return;
const idx = inputBuffer.indexOf("\n");
if (idx == -1) return;
waitQueue.shift()[0](inputBuffer.slice(0, idx));
inputBuffer = inputBuffer.slice(idx + 1);
}
function stdinEndListener() {
haveEOF = true;
for (const [resolve, reject] of waitQueue) {
reject("End-of-file reached");
}
waitQueue = [];
}
function init() {
process.stdin.on("data", stdinDataListener);
process.stdin.on("end", stdinEndListener);
initialised = true;
}
module.exports.init = init;
function end() {
process.stdin.removeListener("data", stdinDataListener);
process.stdin.removeListener("end", stdinEndListener);
process.stdin.end();
}
module.exports.end = end;
function getline() {
return new Promise((resolve, reject) => {
if (haveEOF) {
reject("End-of-file reached");
return;
}
const idx = inputBuffer.indexOf("\n");
if (idx != -1) {
const line = inputBuffer.slice(0, idx);
inputBuffer = inputBuffer.slice(idx + 1);
resolve(line);
} else {
waitQueue.push([resolve, reject]);
}
});
}
module.exports.getline = getline;
async function prompt(str) {
process.stdout.write(str);
return await getline();
}
module.exports.prompt = prompt;
function eof() {
return haveEOF;
}
module.exports.eof = eof;
|