Files
draw/baota_start.js
2025-09-19 00:22:59 +08:00

77 lines
2.4 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.

// 宝塔环境下的Node项目启动脚本
import { spawn } from 'child_process';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// 获取项目根目录
const rootDir = __dirname;
const serverPath = path.join(rootDir, 'server', 'index.js');
// 检查日志目录
const logDir = path.join(rootDir, 'logs');
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir, { recursive: true });
}
// 创建日志文件流
const logFile = path.join(logDir, 'server.log');
const logStream = fs.createWriteStream(logFile, { flags: 'a' });
console.log('启动后端服务器...');
console.log(`日志文件: ${logFile}`);
// 创建前端构建目录
const distDir = path.join(rootDir, 'server', 'dist');
if (!fs.existsSync(distDir)) {
console.log(`创建前端构建目录: ${distDir}`);
fs.mkdirSync(distDir, { recursive: true });
// 如果dist目录不存在尝试从dist目录复制
const srcDistDir = path.join(rootDir, 'dist');
if (fs.existsSync(srcDistDir)) {
console.log(`${srcDistDir} 复制前端文件到 ${distDir}`);
fs.cpSync(srcDistDir, distDir, { recursive: true });
} else {
console.log('警告: 前端构建文件不存在,请先运行 npm run build');
// 创建一个临时index.html避免服务器报错
fs.writeFileSync(path.join(distDir, 'index.html'), '<html><body><h1>抽奖系统</h1><p>前端文件未构建,请先运行 npm run build</p></body></html>');
}
}
// 使用start:node server.js启动服务器
const server = spawn('node', ['server/index.js'], {
cwd: rootDir,
env: {
...process.env,
PORT: 3010,
NODE_ENV: 'production'
},
stdio: ['ignore', 'pipe', 'pipe']
});
console.log('使用启动命令: start:node server.js');
// 将输出写入日志
server.stdout.pipe(logStream);
server.stderr.pipe(logStream);
server.stdout.on('data', (data) => {
console.log(`[服务器输出] ${data.toString().trim()}`);
});
server.stderr.on('data', (data) => {
console.error(`[服务器错误] ${data.toString().trim()}`);
});
server.on('close', (code) => {
console.log(`服务器进程退出,退出码: ${code}`);
logStream.end();
});
console.log(`后端服务已启动,端口: 3010`);
console.log('使用 pm2 或 forever 保持此脚本运行');