-
Notifications
You must be signed in to change notification settings - Fork 242
/
sync-stdio.ts
69 lines (59 loc) · 1.97 KB
/
sync-stdio.ts
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
import * as fs from 'fs';
const STDIN_FD = 0;
const STDOUT_FD = 1;
const STDERR_FD = 2;
const INPUT_BUFFER_SIZE = 1024 * 1024; // not related to max line length
export class SyncStdio {
private readonly inputQueue = new Array<string>();
private currentLine = '';
public writeErrorLine(line: string) {
this.writeBuffer(Buffer.from(`${line}\n`), STDERR_FD);
}
public writeLine(line: string) {
this.writeBuffer(Buffer.from(`${line}\n`), STDOUT_FD);
}
public readLine(): string | undefined {
const buff = Buffer.alloc(INPUT_BUFFER_SIZE);
while (this.inputQueue.length === 0) {
try {
const read = fs.readSync(STDIN_FD, buff, 0, buff.length, null);
if (read === 0) {
return undefined;
}
const str = buff.slice(0, read).toString();
for (const ch of str) {
if (ch === '\n') {
this.inputQueue.push(this.currentLine);
this.currentLine = '';
} else {
this.currentLine += ch;
}
}
} catch (e) {
// HACK: node opens STDIN with O_NONBLOCK, meaning attempts to synchrounously read from it may
// result in EAGAIN. In such cases, the call should be retried until it succeeds. This kind of
// polling may be terribly inefficient, and the "correct" way to address this is to stop
// relying on synchronous reads from STDIN. This is however a non-trivial endeavor, and the
// current state of things is very much broken in node >= 13.2, as can be see in
// https://github.com/aws/aws-cdk/issues/5187
if (e.code !== 'EAGAIN') {
throw e;
}
}
}
const next = this.inputQueue.shift();
return next;
}
private writeBuffer(buffer: Buffer, fd: number) {
let offset = 0;
while (offset < buffer.length) {
try {
offset += fs.writeSync(fd, buffer, offset);
} catch (e) {
if (e.code !== 'EAGAIN') {
throw e;
}
}
}
}
}