IYUUPlus-Windows/server/server.js
2024-06-28 16:13:57 +08:00

81 lines
2.3 KiB
JavaScript

const { spawn, exec } = require('child_process');
const os = require('os');
const path = require('path');
const log = require('electron-log')
function getCmdPath(resourcePath) {
const arch = os.arch();
if (arch === 'x64') {
return path.join(resourcePath, 'run', 'php-8.3.8-x64', 'php.exe');
} else if (arch === 'ia32') {
return path.join(resourcePath, 'run', 'php-8.3.8-x86', 'php.exe');
} else {
log.info("Unsupported architecture:", arch);
process.exit(1);
}
}
let serverProcess = null;
function startServer() {
let resourcePath = process.resourcesPath;
if (resourcePath.includes('node_modules')) {
resourcePath = process.cwd();
}
const cmdPath = getCmdPath(resourcePath);
const args = [path.join(resourcePath, 'iyuu', 'windows.php')];
const workingDirectory = path.resolve(resourcePath);
const env = { ...process.env };
const phpDir = path.dirname(cmdPath);
env.PATH = `${phpDir}${path.delimiter}${env.PATH}`;
serverProcess = spawn(cmdPath, args, {
cwd: workingDirectory,
stdio: ['inherit', 'pipe', 'inherit'],
env: env,
detached: true,
});
serverProcess.stdout.setEncoding('utf8');
serverProcess.stdout.on("data", function (data) {
log.info("[IYUU] 服务启动成功");
});
serverProcess.on("close", function (code) {
log.info("[IYUU] 服务退出:" + code);
});
}
function stopServer() {
if (serverProcess) {
log.info("Killing server process with PID:", serverProcess.pid);
try {
process.kill(-serverProcess.pid, 'SIGTERM');
log.info("后台服务已关闭...");
serverProcess = null;
} catch (err) {
log.error('Error using process.kill:', err);
log.info('Falling back to taskkill');
exec(`taskkill /PID ${serverProcess.pid} /T /F`, (err, stdout, stderr) => {
if (err) {
log.error('Error using taskkill:', err);
} else {
log.info("后台服务已关闭...");
serverProcess = null;
}
});
}
} else {
log.info("No server process to kill.");
}
}
function restartServer() {
stopServer();
startServer();
}
module.exports = { startServer, stopServer, restartServer };