You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123 lines
3.3 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const { spawn } = require('child_process');
const proxyPort = 3000;
const nextPort = 3001;
const goBackendPort = 9999;
// 启动 Next.js 开发服务器
function startNextServer() {
return new Promise((resolve, reject) => {
console.log(`Starting Next.js server on port ${nextPort}...`);
if (process.platform === 'win32') {
// Windows 平台下使用cmd拉起npx
nextProcess = spawn('cmd.exe', ['/c', 'npx', 'next', 'dev', '-p', nextPort.toString()], {
stdio: 'pipe',
env: { ...process.env }
});
} else {
// 其他平台
nextProcess = spawn('npx', ['next', 'dev', '-p', nextPort.toString()], {
stdio: 'pipe',
env: { ...process.env }
});
}
nextProcess.stdout.on('data', (data) => {
const output = data.toString();
console.log(`[Next.js] ${output.trim()}`);
// 检测 Next.js 是否已经启动完成
if (output.includes('Ready') || output.includes('started server')) {
resolve(nextProcess);
}
});
nextProcess.stderr.on('data', (data) => {
console.error(`[Next.js Error] ${data.toString().trim()}`);
});
nextProcess.on('error', (error) => {
console.error('Failed to start Next.js server:', error);
reject(error);
});
// 设置超时
setTimeout(() => {
resolve(nextProcess);
}, 10000);
});
}
// 启动 Express 代理服务器
async function startProxyServer() {
console.log(`Starting Express proxy server on port ${proxyPort}...`);
const app = express();
// Socket.io 代理到 Go 后端
const socketProxy = createProxyMiddleware('/socket.io', {
target: `http://localhost:${goBackendPort}`,
ws: true,
changeOrigin: true,
logLevel: 'debug'
});
// Next.js 代理
const nextProxy = createProxyMiddleware({
target: `http://localhost:${nextPort}`,
changeOrigin: true,
ws: true, // 支持 WebSocket用于热重载
logLevel: 'silent'
});
// 添加代理中间件
app.use('/socket.io', socketProxy);
app.use('/', nextProxy);
// app.on('upgrade', (req, socket, head) => {
// console.log('WebSocket upgrade request received');
// socketProxy(req, socket, head);
// });
app.listen(proxyPort, () => {
console.log(`🚀 Proxy server ready on http://localhost:${proxyPort}`);
console.log(`📡 Proxying Socket.io to http://localhost:${goBackendPort}`);
console.log(`⚛️ Proxying Next.js from http://localhost:${nextPort}`);
});
}
// 主启动函数
async function start() {
try {
// 先启动 Next.js 服务器
const nextProcess = await startNextServer();
// 等待一下确保 Next.js 完全启动
await new Promise(resolve => setTimeout(resolve, 2000));
// 然后启动代理服务器
await startProxyServer();
// 优雅关闭处理
process.on('SIGINT', () => {
console.log('\n🛑 Shutting down servers...');
nextProcess.kill('SIGTERM');
process.exit(0);
});
process.on('SIGTERM', () => {
console.log('\n🛑 Shutting down servers...');
nextProcess.kill('SIGTERM');
process.exit(0);
});
} catch (error) {
console.error('Failed to start servers:', error);
process.exit(1);
}
}
start();