$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