12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- const express = require('express');
- const path = require('path');
- const { spawn } = require('child_process');
- const cors = require('cors');
- const { parseK6StdoutTable, watchClient } = require("./utils");
- const app = express();
- const isDev = process.env.NODE_ENV === 'development';
- const PORT = isDev ? 8080 : 9001;
- const SCREENSHOTS_DIR = path.join(__dirname, 'screenshots');
- const CLIENT_DIST_DIR = isDev ? path.join(__dirname, '../client/dist') : path.join(__dirname, './public');
- // 开发模式下监听client文件变动执行打包脚本
- if (isDev) {
- watchClient()
- }
- // ====== 中间件 ======
- app.use(cors());
- // 静态资源
- app.use('/static', express.static(SCREENSHOTS_DIR));
- app.use(express.static(CLIENT_DIST_DIR));
- // ====== API 路由 ======
- app.get('/api/k6', async (req, res) => {
- const targetUrl = req.query.targetUrl;
- const timeStamp = req.query.timeStamp;
- console.log("targetUrl:", targetUrl);
- console.log("timeStamp:", timeStamp);
- if (!targetUrl || !timeStamp) {
- return res.status(400).json({ error: '缺少 targetUrl 或 timeStamp 参数' });
- }
- // 运行 k6 脚本
- const k6Process = spawn('k6', ['run', '--no-color=false', '--env', 'targetUrl=' + targetUrl, '--env', 'timeStamp=' + timeStamp, './script-browser.js']);
- let outputBuffer = '';
- k6Process.stdout.on('data', (chunk) => {
- outputBuffer += chunk.toString();
- console.log(chunk.toString())
- });
- k6Process.on('close', () => {
- const parsed = parseK6StdoutTable(outputBuffer);
- res.json(parsed); // 返回结构化结果给前端
- });
- });
- // ====== history 路由兼容(放在所有 API 路由之后) ======
- app.get('*', (req, res) => {
- res.sendFile(path.join(CLIENT_DIST_DIR, 'index.html'));
- });
- // ====== 启动服务 ======
- app.listen(PORT, () => {
- console.log(`Express server running at http://localhost:${PORT}`);
- });
|