diff --git a/main.cjs b/main.cjs index bb4aca6..5894957 100644 --- a/main.cjs +++ b/main.cjs @@ -1,41 +1,52 @@ const { app, BrowserWindow } = require('electron'); const path = require('path'); -const { spawn } = require('child_process'); +const { spawn, exec } = require('child_process'); let mainWindow; let serverProcess; -// Функция создания окна function createWindow() { mainWindow = new BrowserWindow({ width: 1200, height: 800, + autoHideMenuBar: true, webPreferences: { nodeIntegration: true, contextIsolation: false - }, - icon: path.join(__dirname, 'public/uikit/bot.png') // Попытка найти иконку + } + }); + + mainWindow.setMenu(null); + + // --- ОБРАБОТЧИК ЗАКРЫТИЯ ОКНА (ВНУТРИ ФУНКЦИИ) --- + mainWindow.on('close', () => { + console.log("⚠️ Окно закрывается."); + + // 1. Пытаемся убить запущенный процесс + if (serverProcess) { + serverProcess.kill('SIGTERM'); + } + + // 2. ЗАПУСКАЕМ ЧИСТКУ ПОРТА + setTimeout(() => { + killPort3000(); + }, 200); }); - // Запускаем сервер startServer(); - // Ждем 1.5 сек для старта сервера и загружаем страницу setTimeout(() => { mainWindow.loadURL('http://localhost:3000'); }, 1500); } function startServer() { - // ИСПРАВЛЕНИЕ: Используем __dirname, который указывает на корень проекта - // Так как main.cjs лежит в корне, __dirname = C:\...\airllm-nodejs const appPath = __dirname; console.log("Запуск сервера из:", appPath); - // Запускаем node server/server.js serverProcess = spawn('node', ['server/server.js'], { - cwd: appPath, // Рабочая директория — корень проекта - shell: true // Нужно для путей с пробелами (Robert Onelli) + cwd: appPath, + shell: true }); serverProcess.stdout.on('data', (data) => { @@ -46,11 +57,54 @@ function startServer() { console.error(`[Ошибка сервера]: ${data}`); }); - // При закрытии окна убиваем сервер - app.on('window-all-closed', () => { - if (serverProcess) serverProcess.kill(); - if (process.platform !== 'darwin') app.quit(); + serverProcess.on('close', (code) => { + console.log(`Сервер завершил работу с кодом ${code}`); }); } +// --- ФУНКЦИЯ: Убийство всех процессов на порту 3000 --- +function killPort3000() { + console.log("🛑 Проверка и очистка порта 3000..."); + + exec('netstat -ano | findstr :3000', (err, stdout, stderr) => { + if (err || !stdout) { + console.log("Порт 3000 свободен."); + return; + } + + const lines = stdout.split('\n'); + const pidsToKill = new Set(); + + lines.forEach(line => { + const parts = line.trim().split(/\s+/); + if (parts.length > 4) { + const pid = parts[parts.length - 1]; + if (pid && line.includes('LISTENING')) { + pidsToKill.add(pid); + } + } + }); + + if (pidsToKill.size > 0) { + console.log(`🔪 Найдено процессов: ${Array.from(pidsToKill).join(', ')}`); + + const killCommand = `taskkill /F /PID ${Array.from(pidsToKill).join(' /PID ')}`; + + exec(killCommand, (killErr) => { + if (killErr) { + console.error("Не удалось убить процессы:", killErr); + } else { + console.log("✅ Процессы на порту 3000 успешно остановлены."); + } + }); + } + }); +} + +app.on('window-all-closed', () => { + if (process.platform !== 'darwin') { + app.quit(); + } +}); + app.whenReady().then(createWindow); \ No newline at end of file diff --git a/public/index.html b/public/index.html index 5448ab0..0f9a1e7 100644 --- a/public/index.html +++ b/public/index.html @@ -7,43 +7,76 @@
-