1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- const { exec } = require('child_process');
- const axios = require('axios');
- const fs = require('fs');
- const path = require('path');
- const constants = require('./constants');
- const utils = require('./utils');
- let serverProcess;
- // 启动 Web API 的函数
- const startServer = () => {
- return new Promise((resolve, reject) => {
- serverProcess = exec(path.join(constants.serverPath, 'server', 'IES.ExamServer.exe'), {
- cwd: `${constants.serverPath}/server`, // 设置工作目录为 server 目录
- stdio: 'inherit'
- });
- serverProcess.stdout.on('data', (data) => {
- console.log(`Server stdout: ${data}`);
- });
- serverProcess.stderr.on('data', (data) => {
- console.log(`Server stderr: ${data}`);
- });
- serverProcess.on('close', (data) => {
- console.log(`Server process exited with code ${data}`);
- reject(new Error(`Server process exited with code ${data}`));
- });
- // 等待 Web API 启动成功
- const checkHealth = async () => {
- try {
- const response = await axios.get(`${constants.baseUrl}/index/health`, {
- httpsAgent: constants.agent
- });
- if (response.status === 200) {
- console.log('Server is up and running!');
- resolve();
- }
- } catch (error) {
- console.log('Waiting for server to start...');
- setTimeout(checkHealth, 1000); // 每隔 1 秒检查一次
- }
- };
- checkHealth();
- });
- };
- // 检查服务器健康状态的函数
- const checkServerHealth = async () => {
- try {
- const response = await axios.get(`${constants.baseUrl}/index/health`, {
- httpsAgent: constants.agent
- });
- if (response.status === 200) {
- console.log('Server is up and running!');
- return true;
- }
- } catch (error) {
- console.log('Server is not running yet.');
- return false;
- }
- };
- // 关闭服务器的函数
- const shutdownServer = async () => {
- if (serverProcess) {
- console.log('Killing server process...');
- serverProcess.kill();
- }
- try {
- console.log('index/shutdown api ...');
- const response = await axios.get(`${constants.baseUrl}/index/shutdown`, {
- httpsAgent: constants.agent
- });
- if (response.status === 200) {
- console.log('Server is shutdown!');
- }
- } catch (error) {
- console.error('关闭.NET Core Web API 时出错:', error);
- }
- };
- module.exports = {
- startServer,
- checkServerHealth,
- shutdownServer
- };
|