import { ChildProcess, fork, ForkOptions } from 'child_process'; class BaseProcess { private process: ChildProcess; status: 'running' | 'stopped' | 'error' = 'stopped'; appPath: string; args: any[] = []; opts: ForkOptions = {}; /* * 重启次数, 默认0, TODO, 错误检测,当重启次数超过一定次数,则认为进程已崩溃 */ restartCount: number = 0; constructor(appPath?: string, args?: any[], opts?: ForkOptions) { this.appPath = appPath; this.args = args || []; this.opts = opts || {}; // this.createProcess(appPath); } createProcess(appPath: string = this.appPath, args: any[] = [], opts: ForkOptions = {}) { if (this.process) { this.process.kill(); } this.appPath = appPath || this.appPath; this.args = args || this.args; this.opts = { ...this.opts, ...opts, }; this.process = fork(appPath, args, { stdio: 'inherit', ...this.opts, env: { ...process.env, NODE_ENV_PARENT: 'fork', ...this.opts?.env, }, }); return this; } kill(signal?: NodeJS.Signals | number) { if (this.process) { this.process.kill(signal); } return this; } public send(message: any) { this.process.send(message); } public on(event: string, callback: (message: any) => void) { this.process.on(event, callback); } public onExit(callback: (code: number) => void) { this.process.on('exit', callback); } public onError(callback: (error: Error) => void) { this.process.on('error', callback); } public onMessage(callback: (message: any) => void) { this.process.on('message', callback); } public onClose(callback: () => void) { this.process.on('close', callback); } public onDisconnect(callback: () => void) { this.process.on('disconnect', callback); } restart() { this.kill(); this.createProcess(); } } export class AssistantProcess extends BaseProcess { constructor(appPath: string) { super(appPath); } }