Files
ggl/start-production.cjs
2025-09-23 08:00:05 +00:00

70 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const { spawn } = require('child_process');
const path = require('path');
const express = require('express');
// 生产环境配置
const API_PORT = process.env.PORT || 4001;
const FRONTEND_PORT = process.env.FRONTEND_PORT || 4002;
const NODE_ENV = 'production';
// 设置环境变量
process.env.NODE_ENV = NODE_ENV;
process.env.PORT = API_PORT;
console.log(`启动生产环境服务器`);
console.log(`后端API端口: ${API_PORT}`);
console.log(`前端静态文件端口: ${FRONTEND_PORT}`);
console.log(`工作目录: ${process.cwd()}`);
// 启动前端静态文件服务
const app = express();
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
const frontendServer = app.listen(FRONTEND_PORT, () => {
console.log(`前端静态文件服务已启动,端口: ${FRONTEND_PORT}`);
});
// 启动后端API服务器
const apiServer = spawn('node', ['--import', 'tsx/esm', 'api/server.ts'], {
stdio: 'inherit',
env: {
...process.env,
NODE_ENV: NODE_ENV,
PORT: API_PORT
}
});
// 处理API服务器进程退出
apiServer.on('close', (code) => {
console.log(`API服务器进程退出退出码: ${code}`);
frontendServer.close();
process.exit(code);
});
// 处理API服务器错误
apiServer.on('error', (err) => {
console.error('启动API服务器时发生错误:', err);
frontendServer.close();
process.exit(1);
});
// 优雅关闭
process.on('SIGINT', () => {
console.log('\n收到 SIGINT 信号,正在关闭服务器...');
frontendServer.close();
apiServer.kill('SIGINT');
});
process.on('SIGTERM', () => {
console.log('\n收到 SIGTERM 信号,正在关闭服务器...');
frontendServer.close();
apiServer.kill('SIGTERM');
});
// 处理前端服务器错误
frontendServer.on('error', (err) => {
console.error('前端静态文件服务器错误:', err);
});