Files
zn-ai/src/main/service/execute-script-service/index.ts
2026-03-11 17:01:48 +08:00

86 lines
2.4 KiB
TypeScript

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<string, any>,
): 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 child = spawn('node', [scriptPath], {
env: {
...process.env,
ROOM_TYPE: String(roomType),
START_DATE: String(startTime),
END_DATE: String(endTime),
OPERATION: String(operation)
},
});
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 脚本时出错',
});
}
});
}
}