Files
ks-app-employment-service/set-node-memory-limit.ps1

84 lines
3.5 KiB
PowerShell
Raw Normal View History

2025-10-21 22:58:47 +08:00
# PowerShell 脚本:设置 Node.js 内存限制环境变量
# 需要以管理员权限运行
Write-Host "================================================" -ForegroundColor Cyan
Write-Host "Node.js 内存限制设置工具" -ForegroundColor Cyan
Write-Host "================================================" -ForegroundColor Cyan
Write-Host ""
# 检查是否以管理员权限运行
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
Write-Host "[警告] 设置系统环境变量需要管理员权限" -ForegroundColor Yellow
Write-Host "将仅为当前用户设置环境变量..." -ForegroundColor Yellow
Write-Host ""
}
# 内存大小选项
Write-Host "请选择内存限制大小:" -ForegroundColor Green
Write-Host "1. 4GB (4096 MB) - 推荐用于小型项目"
Write-Host "2. 8GB (8192 MB) - 推荐用于中型项目 [默认]"
Write-Host "3. 16GB (16384 MB) - 推荐用于大型项目"
Write-Host "4. 自定义大小"
Write-Host ""
$choice = Read-Host "请输入选项 (1-4直接回车使用默认值 8GB)"
$memorySize = 8192
switch ($choice) {
"1" { $memorySize = 4096 }
"2" { $memorySize = 8192 }
"3" { $memorySize = 16384 }
"4" {
$customSize = Read-Host "请输入自定义内存大小 (MB)"
if ($customSize -match '^\d+$') {
$memorySize = [int]$customSize
} else {
Write-Host "[错误] 无效的数字,使用默认值 8192 MB" -ForegroundColor Red
}
}
default { $memorySize = 8192 }
}
$nodeOptions = "--max-old-space-size=$memorySize"
Write-Host ""
Write-Host "将设置 NODE_OPTIONS = $nodeOptions" -ForegroundColor Green
Write-Host "内存限制:$memorySize MB ($($memorySize/1024) GB)" -ForegroundColor Green
Write-Host ""
# 设置环境变量
try {
if ($isAdmin) {
# 设置系统环境变量
[System.Environment]::SetEnvironmentVariable("NODE_OPTIONS", $nodeOptions, [System.EnvironmentVariableTarget]::Machine)
Write-Host "[成功] 已设置系统环境变量(对所有用户生效)" -ForegroundColor Green
} else {
# 设置用户环境变量
[System.Environment]::SetEnvironmentVariable("NODE_OPTIONS", $nodeOptions, [System.EnvironmentVariableTarget]::User)
Write-Host "[成功] 已设置用户环境变量(仅对当前用户生效)" -ForegroundColor Green
}
Write-Host ""
Write-Host "重要提示:" -ForegroundColor Yellow
Write-Host "1. 请重启 HBuilderX 使环境变量生效" -ForegroundColor Yellow
Write-Host "2. 如果问题仍然存在,请尝试增大内存限制" -ForegroundColor Yellow
Write-Host "3. 也可以尝试清理项目缓存(运行 → 清理项目缓存)" -ForegroundColor Yellow
Write-Host ""
} catch {
Write-Host "[错误] 设置环境变量失败:$($_.Exception.Message)" -ForegroundColor Red
Write-Host ""
Write-Host "手动设置方法:" -ForegroundColor Yellow
Write-Host "1. 右键'此电脑' → '属性' → '高级系统设置' → '环境变量'" -ForegroundColor Yellow
Write-Host "2. 在'用户变量'中新建变量:" -ForegroundColor Yellow
Write-Host " 变量名NODE_OPTIONS" -ForegroundColor Yellow
Write-Host " 变量值:$nodeOptions" -ForegroundColor Yellow
Write-Host ""
}
Write-Host "按任意键退出..."
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")