'use strict'; // 双击入口:检查本机 Node、等待服务可访问后再打开浏览器。 const { spawn } = require('node:child_process'); const path = require('node:path'); const [major, minor] = process.versions.node.split('.').map(Number); if (major < 22 || (major === 22 && minor < 16)) { console.error('请先安装 Node.js 24 LTS 或更新的LTS版本,再双击启动。不需要 npm install。'); process.exit(1); } const mode = process.env.APP_MODE || 'demo'; const port = Number(process.env.PORT || (mode === 'demo' ? 3100 : 3101)); const url = `http://127.0.0.1:${port}`; function open() { if (process.platform === 'win32') spawn('cmd', ['/c', 'start', '', url], { stdio: 'ignore' }); else if (process.platform === 'darwin') spawn('open', [url], { stdio: 'ignore' }); else console.log('请打开:' + url); } async function status() { try { const r = await fetch(url + '/api/session', { signal: AbortSignal.timeout(700) }); return r.ok ? await r.json() : null; } catch { return null; } } (async () => { const existing = await status(); if (existing) { if (existing.mode !== mode) throw new Error('端口被另一种运行模式占用,请先关闭对应启动窗口。'); console.log('系统已经运行,打开现有页面。'); open(); return; } const child = spawn(process.execPath, [path.join(__dirname, 'server.js')], { stdio: 'inherit', env: { ...process.env, APP_MODE: mode, PORT: String(port), HOST: '127.0.0.1' }, }); let exited = false; child.on('exit', code => { exited = true; process.exitCode = code || 0; }); for (let i = 0; i < 30 && !exited; i++) { const s = await status(); if (s?.mode === mode) { open(); return; } await new Promise(r => setTimeout(r, 300)); } if (!exited) console.error('启动时间较长,请根据上方提示检查,服务地址:' + url); })().catch(e => { console.error(e.message); process.exitCode = 1; });