Files
scanner_record/desktop/src/main.js
T

66 lines
2.0 KiB
JavaScript

const { app, Tray, Menu, nativeImage } = require('electron')
const { spawn, exec } = require('child_process')
const http = require('http')
const path = require('path')
const PROJECT_DIR = path.resolve(__dirname, '../../project')
const TSX = path.join(PROJECT_DIR, 'node_modules', 'tsx', 'dist', 'cli.mjs')
let backend = null
let tray = null
let isRunning = false
const ICON = nativeImage.createFromBuffer(Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVR4nO3OIQEAAAgDMHJg6Ul1iHEzMb/q2UsqAQEBAQEBAQEBAQEBAQGBdOABvyXoW2Q1L3wAAAAASUVORK5CYII=',
'base64'
))
function updateMenu() {
tray.setContextMenu(Menu.buildFromTemplate([
{ label: '打开页面', click: () => exec('start http://localhost:3000') },
{ type: 'separator' },
{ label: '启动服务', enabled: !isRunning, click: startBackend },
{ label: '停止服务', enabled: isRunning, click: () => stopBackend() },
{ type: 'separator' },
{ label: '退出', click: () => { killBackend(); app.quit() } },
]))
}
function startBackend() {
if (backend) return
backend = spawn('node', [TSX, 'src/index.ts'], {
cwd: PROJECT_DIR,
stdio: ['ignore', 'pipe', 'pipe'],
env: { ...process.env, PORT: process.env.PORT || '3000' },
windowsHide: true,
})
backend.stdout.pipe(process.stdout)
backend.stderr.pipe(process.stderr)
isRunning = true
updateMenu()
backend.on('exit', () => { backend = null; isRunning = false; updateMenu() })
}
function stopBackend() {
if (!backend) return
http.get('http://localhost:3000/api/shutdown').on('error', () => {})
setTimeout(killBackend, 1000)
}
function killBackend() {
if (!backend) return
try { backend.kill('SIGTERM') } catch {}
backend = null
isRunning = false
updateMenu()
}
app.whenReady().then(() => {
tray = new Tray(ICON.resize({ width: 16, height: 16 }))
tray.setToolTip('质量追溯系统')
updateMenu()
startBackend()
})
app.on('window-all-closed', () => {})
app.on('before-quit', () => killBackend())