refactor: B2 - in-process backend load (no spawn)

This commit is contained in:
zlm committed 2026-06-10 14:18:18 +08:00
1 parent 4e02b8605d
commit 1ad9a59f76
5 files changed
+49 -71

No files matched your search

+4 -5
View File
@@ -2,15 +2,14 @@
"name": "scanner-record-desktop", "name": "scanner-record-desktop",
"version": "1.0.0", "version": "1.0.0",
"private": true, "private": true,
"main": "dist/main.js", "main": "src/main.ts",
"scripts": { "scripts": {
"dev": "tsc && electron dist/main.js", "dev": "electron -r tsx src/main.ts",
"build": "tsc && electron-builder --win portable", "build": "electron-builder --win portable"
"pack": "tsc && electron-builder --win portable --dir"
}, },
"devDependencies": { "devDependencies": {
"electron": "^34.0.0", "electron": "^34.0.0",
"electron-builder": "^25.0.0", "electron-builder": "^25.0.0",
"typescript": "^5.7.0" "tsx": "^4.19.0"
} }
} }
+37 -43
View File
@@ -1,15 +1,9 @@
import { app, Tray, Menu, BrowserWindow, nativeImage, ipcMain } from 'electron' import { app, Tray, Menu, BrowserWindow, nativeImage, ipcMain } from 'electron'
import { spawn, ChildProcess } from 'child_process'
import fs from 'fs' import fs from 'fs'
import path from 'path' import path from 'path'
/* ===== Paths ===== */ /* ===== Paths ===== */
const IS_PACKAGED = app.isPackaged const PROJECT_DIR = path.resolve(process.cwd(), '../project')
const ROOT = IS_PACKAGED
? path.dirname(process.execPath)
: path.resolve(__dirname, '../..')
const PROJECT_DIR = path.join(ROOT, 'project')
const LOG_DIR = path.join(PROJECT_DIR, 'logs') const LOG_DIR = path.join(PROJECT_DIR, 'logs')
let isQuitting = false 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 }) 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 ===== */ /* ===== Log window ===== */
let logWindow: BrowserWindow | null = null let logWindow: BrowserWindow | null = null
let logBuffer: string[] = [] let logBuffer: string[] = []
@@ -69,7 +31,7 @@ function createLogWindow(): void {
title: '质量追溯系统 - 日志', title: '质量追溯系统 - 日志',
icon: createIcon(), icon: createIcon(),
webPreferences: { webPreferences: {
preload: path.join(__dirname, 'preload.js'), preload: path.join(process.cwd(), 'src', 'preload.js'),
contextIsolation: true, nodeIntegration: false, contextIsolation: true, nodeIntegration: false,
}, },
}) })
@@ -83,6 +45,35 @@ function toggleWindow(): void {
logWindow?.isVisible() ? logWindow?.hide() : (logWindow?.show(), logWindow?.focus()) 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 ===== */ /* ===== Log window HTML ===== */
const LOG_HTML = `<!DOCTYPE html> const LOG_HTML = `<!DOCTYPE html>
<html><head><meta charset="utf-8"> <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: () => { try { require('child_process').exec('start http://localhost:3000') } catch {} } },
{ label: '显示/隐藏 日志', click: toggleWindow }, { label: '显示/隐藏 日志', click: toggleWindow },
{ type: 'separator' }, { type: 'separator' },
{ label: '退出', click: () => { isQuitting = true; stopBackend(); app.quit() } }, { label: '退出', click: () => { isQuitting = true; app.quit() } },
])) ]))
tray.on('double-click', toggleWindow) tray.on('double-click', toggleWindow)
} }
/* ===== App lifecycle ===== */ /* ===== App lifecycle ===== */
app.whenReady().then(() => { app.whenReady().then(() => {
// Ensure data and logs directories exist
;['data', 'logs'].forEach(d => { ;['data', 'logs'].forEach(d => {
const p = path.join(PROJECT_DIR, d) const p = path.join(PROJECT_DIR, d)
if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true }) if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true })
}) })
hookConsole() // intercept console.log before backend loads
createTray() createTray()
createLogWindow() createLogWindow()
startBackend() startBackend()
@@ -137,6 +128,9 @@ app.whenReady().then(() => {
}) })
app.on('window-all-closed', () => { /* keep running in tray */ }) 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) ipcMain.handle('get-log-buffer', () => logBuffer)
+8
View File
@@ -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'),
})
-8
View File
@@ -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'),
})
-15
View File
@@ -1,15 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"sourceMap": true
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}