process-manager.mjs 2.62 KB
// ============================================================================
// Process Manager Module - 子进程生命周期管理
// Singleton Pattern: 全局唯一的进程管理器
// ============================================================================

import { spawn } from "node:child_process";

let currentProcess = null;
let isRunning = false;

/**
 * 获取当前是否正在运行
 */
export function getIsRunning() {
	return isRunning;
}

/**
 * 设置运行状态
 */
export function setIsRunning(value) {
	isRunning = value;
}

/**
 * 获取当前进程
 */
export function getCurrentProcess() {
	return currentProcess;
}

/**
 * 设置当前进程
 */
export function setCurrentProcess(proc) {
	currentProcess = proc;
}

/**
 * 异步执行子进程(流式输出)
 * @param {string} command - 命令
 * @param {string[]} args - 参数数组
 * @param {object} options - spawn 选项
 * @param {Function} onOutput - 输出回调 (line, stream) => void
 * @returns {Promise<{stdout: string, stderr: string, status: number}>}
 */
export function spawnAsync(command, args, options, onOutput) {
	return new Promise((resolve, reject) => {
		const child = spawn(command, args, {
			...options,
			stdio: ["ignore", "pipe", "pipe"],
		});

		let stdout = "";
		let stderr = "";
		let stdoutBuffer = "";

		child.stdout.on("data", (data) => {
			stdout += data;
			if (onOutput) {
				stdoutBuffer += data.toString();
				const lines = stdoutBuffer.split("\n");
				stdoutBuffer = lines.pop() || "";
				for (const line of lines) {
					if (line) onOutput(line, "stdout");
				}
			}
		});

		child.stderr.on("data", (data) => {
			stderr += data;
			if (onOutput) {
				const lines = data.toString().split("\n");
				for (const line of lines) {
					if (line) onOutput(line, "stderr");
				}
			}
		});

		child.on("exit", (code) => {
			if (onOutput && stdoutBuffer) {
				onOutput(stdoutBuffer, "stdout");
			}
			resolve({ stdout, stderr, status: code });
		});

		child.on("error", (err) => {
			reject(err);
		});

		if (options?.timeout) {
			setTimeout(() => {
				child.kill();
				reject(new Error(`Process timed out after ${options.timeout}ms`));
			}, options.timeout);
		}
	});
}

/**
 * 停止当前运行的进程
 */
export async function stopCurrentProcess() {
	if (currentProcess) {
		currentProcess.kill("SIGTERM");
		await new Promise((r) => setTimeout(r, 1000));
		if (currentProcess) {
			currentProcess.kill("SIGKILL");
			await new Promise((r) => setTimeout(r, 500));
		}
	}
}

/**
 * 读取 JSON 文件
 */
export function readJson(filePath) {
	try {
		return JSON.parse(fs.readFileSync(filePath, "utf8"));
	} catch {
		return null;
	}
}