refactor: B2 - in-process backend load (no spawn)
This commit is contained in:
1 parent
4e02b8605d
commit
1ad9a59f76
5 files changed
+49
-71
No files matched your search
+37
-43
@@ -1,15 +1,9 @@
|
||||
import { app, Tray, Menu, BrowserWindow, nativeImage, ipcMain } from 'electron'
|
||||
import { spawn, ChildProcess } from 'child_process'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
/* ===== Paths ===== */
|
||||
const IS_PACKAGED = app.isPackaged
|
||||
const ROOT = IS_PACKAGED
|
||||
? path.dirname(process.execPath)
|
||||
: path.resolve(__dirname, '../..')
|
||||
|
||||
const PROJECT_DIR = path.join(ROOT, 'project')
|
||||
const PROJECT_DIR = path.resolve(process.cwd(), '../project')
|
||||
const LOG_DIR = path.join(PROJECT_DIR, 'logs')
|
||||
let isQuitting = false
|
||||
|
||||
@@ -19,38 +13,6 @@ function createIcon(size = 32): Electron.NativeImage {
|
||||
return nativeImage.createFromBuffer(Buffer.from(ICON_B64, 'base64')).resize({ width: size, height: size })
|
||||
}
|
||||
|
||||
/* ===== Backend process ===== */
|
||||
let backend: ChildProcess | null = null
|
||||
|
||||
function startBackend(): void {
|
||||
broadcastLog('[后端] 正在启动...')
|
||||
|
||||
backend = spawn('npx', ['tsx', 'src/index.ts'], {
|
||||
cwd: PROJECT_DIR,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: { ...process.env, PORT: process.env.PORT || '3000' },
|
||||
shell: process.platform === 'win32', // Windows 需要 shell 运行 .cmd 文件
|
||||
windowsHide: true,
|
||||
})
|
||||
|
||||
backend.on('error', (err) => broadcastLog(`[后端] 启动失败: ${err.message}`))
|
||||
|
||||
backend.stdout?.on('data', (d: Buffer) => {
|
||||
for (const line of d.toString().split('\n').filter(Boolean)) broadcastLog(line)
|
||||
})
|
||||
backend.stderr?.on('data', (d: Buffer) => {
|
||||
for (const line of d.toString().split('\n').filter(Boolean)) broadcastLog(`[E] ${line}`)
|
||||
})
|
||||
backend.on('exit', (code) => {
|
||||
broadcastLog(`[后端] 进程退出 (code=${code}),3s 后重启`)
|
||||
setTimeout(startBackend, 3000)
|
||||
})
|
||||
}
|
||||
|
||||
function stopBackend(): void {
|
||||
if (backend) { backend.kill('SIGTERM'); backend = null }
|
||||
}
|
||||
|
||||
/* ===== Log window ===== */
|
||||
let logWindow: BrowserWindow | null = null
|
||||
let logBuffer: string[] = []
|
||||
@@ -69,7 +31,7 @@ function createLogWindow(): void {
|
||||
title: '质量追溯系统 - 日志',
|
||||
icon: createIcon(),
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.js'),
|
||||
preload: path.join(process.cwd(), 'src', 'preload.js'),
|
||||
contextIsolation: true, nodeIntegration: false,
|
||||
},
|
||||
})
|
||||
@@ -83,6 +45,35 @@ function toggleWindow(): void {
|
||||
logWindow?.isVisible() ? logWindow?.hide() : (logWindow?.show(), logWindow?.focus())
|
||||
}
|
||||
|
||||
/* ===== Intercept backend logs ===== */
|
||||
function hookConsole(): void {
|
||||
const origLog = console.log
|
||||
const origError = console.error
|
||||
const origWarn = console.warn
|
||||
|
||||
console.log = (...args: any[]) => {
|
||||
origLog(...args)
|
||||
const line = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')
|
||||
broadcastLog(line)
|
||||
}
|
||||
console.error = (...args: any[]) => {
|
||||
origError(...args)
|
||||
const line = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')
|
||||
broadcastLog(`[E] ${line}`)
|
||||
}
|
||||
console.warn = (...args: any[]) => {
|
||||
origWarn(...args)
|
||||
const line = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')
|
||||
broadcastLog(`[W] ${line}`)
|
||||
}
|
||||
}
|
||||
|
||||
/* ===== Start backend in-process ===== */
|
||||
async function startBackend(): Promise<void> {
|
||||
broadcastLog('[后端] 正在加载...')
|
||||
await import(path.join(PROJECT_DIR, 'src/index.ts'))
|
||||
}
|
||||
|
||||
/* ===== Log window HTML ===== */
|
||||
const LOG_HTML = `<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8">
|
||||
@@ -116,19 +107,19 @@ function createTray(): void {
|
||||
{ label: '打开页面', click: () => { try { require('child_process').exec('start http://localhost:3000') } catch {} } },
|
||||
{ label: '显示/隐藏 日志', click: toggleWindow },
|
||||
{ type: 'separator' },
|
||||
{ label: '退出', click: () => { isQuitting = true; stopBackend(); app.quit() } },
|
||||
{ label: '退出', click: () => { isQuitting = true; app.quit() } },
|
||||
]))
|
||||
tray.on('double-click', toggleWindow)
|
||||
}
|
||||
|
||||
/* ===== App lifecycle ===== */
|
||||
app.whenReady().then(() => {
|
||||
// Ensure data and logs directories exist
|
||||
;['data', 'logs'].forEach(d => {
|
||||
const p = path.join(PROJECT_DIR, d)
|
||||
if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true })
|
||||
})
|
||||
|
||||
hookConsole() // intercept console.log before backend loads
|
||||
createTray()
|
||||
createLogWindow()
|
||||
startBackend()
|
||||
@@ -137,6 +128,9 @@ app.whenReady().then(() => {
|
||||
})
|
||||
|
||||
app.on('window-all-closed', () => { /* keep running in tray */ })
|
||||
app.on('before-quit', () => { isQuitting = true; stopBackend() })
|
||||
app.on('before-quit', () => {
|
||||
isQuitting = true
|
||||
process.emit('SIGINT') // trigger backend's cleanup (scanner.stop, server close)
|
||||
})
|
||||
|
||||
ipcMain.handle('get-log-buffer', () => logBuffer)
|
||||
@@ -0,0 +1,8 @@
|
||||
const { contextBridge, ipcRenderer } = require('electron')
|
||||
|
||||
contextBridge.exposeInMainWorld('electronAPI', {
|
||||
onLog: (callback) => {
|
||||
ipcRenderer.on('log', (_event, line) => callback(line))
|
||||
},
|
||||
getLogBuffer: () => ipcRenderer.invoke('get-log-buffer'),
|
||||
})
|
||||
@@ -1,8 +0,0 @@
|
||||
import { contextBridge, ipcRenderer } from 'electron'
|
||||
|
||||
contextBridge.exposeInMainWorld('electronAPI', {
|
||||
onLog: (callback: (line: string) => void) => {
|
||||
ipcRenderer.on('log', (_event, line: string) => callback(line))
|
||||
},
|
||||
getLogBuffer: () => ipcRenderer.invoke('get-log-buffer'),
|
||||
})
|
||||
Reference in new issue
Block a user