示例工程 03-process-model
03-process-model/demo-02-utility-process/main.ts
import { app, utilityProcess } from "electron";
import path from "node:path";
const isUtility = process.env.UTILITY_MODE === "1";
if (isUtility) {
// 同一份脚本在 utility 模式下只监听 parentPort,不创建窗口。
const parentPort = (
process as unknown as {
parentPort?: {
on: (event: "message", cb: (event: { data: unknown }) => void) => void;
postMessage: (message: unknown) => void;
};
}
).parentPort;
parentPort?.on("message", (event) => {
const n = (event.data as { n?: number }).n ?? 0;
let sum = 0;
for (let index = 1; index <= n; index += 1) sum += index;
parentPort.postMessage({ sum });
});
} else {
app.whenReady().then(async () => {
const child = utilityProcess.fork(path.join(__dirname, "main.js"), [], {
env: { ...process.env, UTILITY_MODE: "1" },
});
const sum = await new Promise<number>((resolve, reject) => {
const timer = setTimeout(() => {
child.kill();
reject(new Error("utility timeout"));
}, 5000);
child.once("spawn", () => {
child.postMessage({ n: 100 });
});
child.on("message", (message) => {
const value = (message as { sum?: number }).sum;
if (typeof value === "number") {
clearTimeout(timer);
child.kill();
resolve(value);
}
});
child.on("exit", (code) => {
if (code !== 0) {
clearTimeout(timer);
reject(new Error(`utility exit ${code}`));
}
});
});
console.log(JSON.stringify({ evt: "smoke", ok: sum === 5050, sum }));
app.quit();
});
app.on("window-all-closed", () => {
app.quit();
});
}