forked from coder/code-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathipc.ts
More file actions
76 lines (65 loc) · 1.69 KB
/
ipc.ts
File metadata and controls
76 lines (65 loc) · 1.69 KB
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
import { EventEmitter } from "events";
import { ChildProcess } from "child_process";
export interface IpcMessage {
readonly event: string;
readonly args: any[]; // tslint:disable-line no-any
}
export class StdioIpcHandler extends EventEmitter {
private isListening: boolean = false;
public constructor(
private readonly childProcess?: ChildProcess,
) {
super();
}
// tslint:disable-next-line no-any
public on(event: string, cb: (...args: any[]) => void): this {
this.listen();
return super.on(event, cb);
}
// tslint:disable-next-line no-any
public once(event: string, cb: (...args: any[]) => void): this {
this.listen();
return super.once(event, cb);
}
// tslint:disable-next-line no-any
public addListener(event: string, cb: (...args: any[]) => void): this {
this.listen();
return super.addListener(event, cb);
}
// tslint:disable-next-line no-any
public send(event: string, ...args: any[]): void {
const msg: IpcMessage = {
event,
args,
};
const d = JSON.stringify(msg);
if (this.childProcess) {
this.childProcess.stdin.write(d + "\n");
} else {
process.stdout.write(d);
}
}
private listen(): void {
if (this.isListening) {
return;
}
// tslint:disable-next-line no-any
const onData = (data: any): void => {
try {
const d = JSON.parse(data.toString()) as IpcMessage;
this.emit(d.event, ...d.args);
} catch (ex) {
if (!this.childProcess) {
process.stderr.write(`Failed to parse incoming data: ${ex.message}`);
}
}
};
if (this.childProcess) {
this.childProcess.stdout.resume();
this.childProcess.stdout.on("data", onData);
} else {
process.stdin.resume();
process.stdin.on("data", onData);
}
}
}