import { EventEmitter } from 'events'; import { spawn } from 'child_process'; import log from 'electron-log'; export class executeScriptService extends EventEmitter { // 执行脚本 async executeScript( scriptPath: string, options: Record, ): Promise<{ success: boolean; exitCode: number | null; stdoutTail: string; stderrTail: string; error?: string }> { const MAX_TAIL = 32 * 1024; const appendTail = (current: string, chunk: string) => { const next = current + chunk; return next.length > MAX_TAIL ? next.slice(next.length - MAX_TAIL) : next; }; return await new Promise((resolve) => { try { const roomType = options?.roomType ?? ''; const startTime = options?.startTime ?? ''; const endTime = options?.endTime ?? ''; const operation = options?.operation ?? ''; const tabIndex = options?.tabIndex ?? ''; const channels = options?.channels ?? ''; const startTabIndex = options?.startTabIndex ?? ''; const child = spawn(process.execPath, [scriptPath], { env: { ...process.env, ELECTRON_RUN_AS_NODE: '1', ROOM_TYPE: String(roomType), START_DATE: String(startTime), END_DATE: String(endTime), OPERATION: String(operation), TAB_INDEX: String(tabIndex), CHANNELS: typeof channels === 'string' ? channels : JSON.stringify(channels), START_TAB_INDEX: String(startTabIndex), }, }); let stdoutTail = ''; let stderrTail = ''; child.stdout?.on('data', (data: Buffer) => { const text = data.toString(); stdoutTail = appendTail(stdoutTail, text); log.info(`stdout: ${text}`); }); child.stderr?.on('data', (data: Buffer) => { const text = data.toString(); stderrTail = appendTail(stderrTail, text); log.info(`stderr: ${text}`); }); child.on('error', (err: any) => { resolve({ success: false, exitCode: null, stdoutTail, stderrTail, error: err?.message || 'Failed to start script process', }); }); child.on('close', (code: number | null) => { log.info(`子进程退出,退出码 ${code}`); resolve({ success: code === 0, exitCode: code, stdoutTail, stderrTail, ...(code === 0 ? {} : { error: `Script exited with code ${code}` }), }); }); } catch (error: any) { resolve({ success: false, exitCode: null, stdoutTail: '', stderrTail: '', error: error?.message || '运行 Node 脚本时出错', }); } }); } }