index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const express = require('express');
  2. const path = require('path');
  3. const { spawn } = require('child_process');
  4. const cors = require('cors');
  5. const { parseK6StdoutTable, watchClient } = require("./utils");
  6. const app = express();
  7. const isDev = process.env.NODE_ENV === 'development';
  8. const PORT = isDev ? 8080 : 9001;
  9. const SCREENSHOTS_DIR = path.join(__dirname, 'screenshots');
  10. const CLIENT_DIST_DIR = isDev ? path.join(__dirname, '../client/dist') : path.join(__dirname, './public');
  11. // 开发模式下监听client文件变动执行打包脚本
  12. if (isDev) {
  13. watchClient()
  14. }
  15. // ====== 中间件 ======
  16. app.use(cors());
  17. // 静态资源
  18. app.use('/static', express.static(SCREENSHOTS_DIR));
  19. app.use(express.static(CLIENT_DIST_DIR));
  20. // ====== API 路由 ======
  21. app.get('/api/k6', async (req, res) => {
  22. const targetUrl = req.query.targetUrl;
  23. const timeStamp = req.query.timeStamp;
  24. console.log("targetUrl:", targetUrl);
  25. console.log("timeStamp:", timeStamp);
  26. if (!targetUrl || !timeStamp) {
  27. return res.status(400).json({ error: '缺少 targetUrl 或 timeStamp 参数' });
  28. }
  29. // 运行 k6 脚本
  30. const k6Process = spawn('k6', ['run', '--no-color=false', '--env', 'targetUrl=' + targetUrl, '--env', 'timeStamp=' + timeStamp, './script-browser.js']);
  31. let outputBuffer = '';
  32. k6Process.stdout.on('data', (chunk) => {
  33. outputBuffer += chunk.toString();
  34. console.log(chunk.toString())
  35. });
  36. k6Process.on('close', () => {
  37. const parsed = parseK6StdoutTable(outputBuffer);
  38. res.json(parsed); // 返回结构化结果给前端
  39. });
  40. });
  41. // ====== history 路由兼容(放在所有 API 路由之后) ======
  42. app.get('*', (req, res) => {
  43. res.sendFile(path.join(CLIENT_DIST_DIR, 'index.html'));
  44. });
  45. // ====== 启动服务 ======
  46. app.listen(PORT, () => {
  47. console.log(`Express server running at http://localhost:${PORT}`);
  48. });