-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchild-process.ts
83 lines (75 loc) · 2.12 KB
/
child-process.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { spawn as nodeSpawn } from "node:child_process";
import type { Operation, Stream } from "effection";
import {
action,
createSignal,
resource,
spawn,
withResolvers,
} from "effection";
export interface ProcessResult {
code: number;
signal?: NodeJS.Signals;
}
export interface Process extends Operation<ProcessResult> {
stdout: Stream<string, void>;
stderr: Stream<string, void>;
send(signal: NodeJS.Signals): void;
}
export function useProcess(command: string): Operation<Process> {
return resource(function* (provide) {
let closed = withResolvers<ProcessResult>();
let stdout = createSignal<string, void>();
let stderr = createSignal<string, void>();
let nodeproc = nodeSpawn(command, {
shell: true,
stdio: "pipe",
});
// fail on an "error" event, but only until the process is successfully spawned.
yield* spawn(function* () {
yield* spawn(() =>
action<void>((_, reject) => {
nodeproc.on("error", reject);
return () => nodeproc.off("error", reject);
})
);
yield* action((resolve) => {
nodeproc.on("spawn", resolve);
return () => nodeproc.off("spawn", resolve);
});
});
let onstdout = (chunk: unknown) => {
stdout.send(String(chunk));
};
let onstderr = (chunk: unknown) => {
stderr.send(String(chunk));
};
let onclose = (code: number, signal?: NodeJS.Signals) => {
stdout.close();
stderr.close();
closed.resolve({ code, signal });
};
try {
nodeproc.stdout.on("data", onstdout);
nodeproc.stderr.on("data", onstderr);
nodeproc.on("close", onclose);
yield* provide({
[Symbol.iterator]: closed.operation[Symbol.iterator],
stdout,
stderr,
*send(signal) {
nodeproc.kill(signal);
},
});
} finally {
nodeproc.kill("SIGINT");
nodeproc.kill("SIGTERM");
yield* closed.operation;
stdout.close();
stderr.close();
nodeproc.stdout.off("data", onstdout);
nodeproc.stderr.off("data", onstderr);
nodeproc.off("close", onclose);
}
});
}