feat: 添加Windows PowerShell重启脚本

添加restart.ps1脚本来管理服务器进程的启动、停止和重启功能,
包括PID文件管理和端口检测。同时创建了logs/server.pid文件来
存储服务器进程ID。
```
This commit is contained in:
2026-03-20 11:54:13 +08:00
parent f8374f5e0d
commit 89d0abd44c
2 changed files with 101 additions and 0 deletions

100
restart.ps1 Normal file
View File

@@ -0,0 +1,100 @@
$ErrorActionPreference = 'Stop'
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$LogDir = Join-Path $ScriptDir 'logs'
$PidFile = Join-Path $LogDir 'server.pid'
$LogFile = Join-Path $LogDir 'server.log'
New-Item -ItemType Directory -Force -Path $LogDir | Out-Null
function Get-PortFromEnvFile {
$envFile = Join-Path $ScriptDir '.env'
if (-not (Test-Path $envFile)) {
return $null
}
$line = Get-Content $envFile | Where-Object { $_ -match '^PORT=' } | Select-Object -Last 1
if (-not $line) {
return $null
}
return ($line -replace '^PORT=', '').Trim()
}
function Get-ProjectServerProcesses {
Get-CimInstance Win32_Process | Where-Object {
$_.Name -eq 'node.exe' -and
$_.CommandLine -like '*src/server.js*' -and
$_.CommandLine -like "*$ScriptDir*"
}
}
function Stop-ExistingServer {
$processes = @(Get-ProjectServerProcesses)
if ($processes.Count -eq 0) {
Write-Host "No existing server process found for $ScriptDir"
return
}
$ids = $processes | ForEach-Object { $_.ProcessId }
Write-Host ("Stopping existing server process(es): " + ($ids -join ', '))
foreach ($process in $processes) {
Stop-Process -Id $process.ProcessId -Force -ErrorAction SilentlyContinue
}
Start-Sleep -Seconds 2
}
function Start-Server {
$port = if ($env:PORT) { $env:PORT } else { Get-PortFromEnvFile }
if (-not $port) { $port = '5000' }
Write-Host "Starting server from $ScriptDir on port $port"
$command = "Set-Location -LiteralPath '$ScriptDir'; node src/server.js *>> '$LogFile'"
$process = Start-Process -FilePath 'powershell.exe' `
-ArgumentList '-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', $command `
-WindowStyle Hidden `
-PassThru
Set-Content -Path $PidFile -Value $process.Id
Write-Host "Started PID: $($process.Id)"
return $port
}
function Show-Status {
param(
[string]$Port
)
Start-Sleep -Seconds 2
Write-Host ''
Write-Host 'Active project server process(es):'
$processes = @(Get-ProjectServerProcesses)
if ($processes.Count -eq 0) {
Write-Host 'None'
} else {
$processes | Select-Object ProcessId, Name, CommandLine | Format-Table -AutoSize
}
Write-Host ''
Write-Host 'Port check:'
Get-NetTCPConnection -LocalPort ([int]$Port) -State Listen -ErrorAction SilentlyContinue |
Select-Object LocalAddress, LocalPort, OwningProcess | Format-Table -AutoSize
Write-Host ''
Write-Host 'Recent log output:'
if (Test-Path $LogFile) {
Get-Content $LogFile -Tail 30
} else {
Write-Host 'No log file yet.'
}
}
Stop-ExistingServer
$port = Start-Server
Show-Status -Port $port