| 2 | import { EventEmitter } from "events"; |
| 3 | |
| 4 | export class ShellProcess extends EventEmitter { |
| 5 | child: ChildProcess; |
| 6 | stdout: string = ""; |
| 7 | stdoutTimeout?: NodeJS.Timeout; |
| 8 | boundStdoutHandler: (data: string) => void = this.stdoutHandler.bind(this); |
| 9 | |
| 10 | constructor(command: string) { |
| 11 | super(); |
| 12 | this.child = spawn(command, { shell: true }); |
| 13 | this.child.stdout?.on("data", this.boundStdoutHandler); |
| 14 | this.child.stderr?.on("data", this.boundStdoutHandler); |
| 15 | this.child.once("close", (code) => { |
| 16 | if (this.stdoutTimeout) { |
| 17 | clearTimeout(this.stdoutTimeout); |
| 18 | } |
| 19 | this.child.stdout?.off("data", this.boundStdoutHandler); |
| 20 | this.child.stderr?.off("data", this.boundStdoutHandler); |
| 21 | this.kill(); |
| 22 | this.emit("close", code); |
| 23 | }); |
| 24 | } |
| 25 | |
| 26 | get pid(): number { |
| 27 | return this.child.pid!; |
| 28 | } |
| 29 | |
| 30 | write(data: string) { |
| 31 | this.child.stdin?.write(data); |
| 32 | } |
| 33 | |
| 34 | kill(signal?: NodeJS.Signals) { |
| 35 | this.child.kill(signal); |
| 36 | } |
| 37 | |
| 38 | stdoutHandler(data: string) { |
| 39 | this.stdout += data; |
| 40 | if (this.stdoutTimeout) { |
| 41 | clearTimeout(this.stdoutTimeout); |
| 42 | } |
| 43 | this.stdoutTimeout = setTimeout(() => { |
| 44 | this.emit("stdout", this.stdout); |
| 45 | this.stdout = ""; |
| 46 | }, 2000); |
| 47 | } |
| 48 | } |
nothing calls this directly
no outgoing calls
no test coverage detected