process-manager.mjs
2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
// ============================================================================
// 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;
}
}