Node.js® 是一个免费、开源、跨平台的 JavaScript 运行时环境,它让开发人员能够创建服务器、 Web 应用、命令行工具和脚本。
https://nodejs.org/dist/v24.14.0/node-v24.14.0-x64.msi权限先行:先执行 Set-ExecutionPolicy,是为了防止你后续在运行 npm config 或其他命令时,系统因为权限策略弹出一堆红色报错。
路径后补:通过脚本动态获取 nodeDir 和 npmPrefix,可以确保即使你的 Node.js 没有装在 C 盘,环境变量也能指对地方。
持久生效:使用了 [System.Environment] 方式写入,这比临时修改 $env:Path 更彻底,重启电脑配置也不会丢。
# 1. 核心权限解锁 (解决 npm.ps1 无法运行或禁止运行脚本的问题)
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
Write-Host ">>> 系统策略已解锁,脚本执行权限已下放 <<<" -ForegroundColor Cyan
# 2. 自动探测 Node.js 安装路径 (默认路径或当前已识别路径)
$nodeDir = if (Get-Command node.exe -ErrorAction SilentlyContinue) {
Split-Path (Get-Command node.exe).Source
} else {
"C:\Program Files\nodejs"
}
# 3. 获取 NPM 全局包存放路径
$npmPrefix = (cmd /c "npm config get prefix").Trim()
Write-Host ">>> 正在写入 Node.js 环境路径..." -ForegroundColor Cyan
# 4. 永久写入用户环境变量 (Path)
# 脚本会自动检查路径是否存在,避免重复添加导致 Path 混乱
$currentPath = [System.Environment]::GetEnvironmentVariable("Path", "User")
$pathsToAdd = @($nodeDir, $npmPrefix)
foreach ($path in $pathsToAdd) {
if ($currentPath -notlike "*$path*") {
$currentPath = "$path;" + $currentPath
Write-Host "已添加路径: $path" -ForegroundColor Green
}
}
[System.Environment]::SetEnvironmentVariable("Path", $currentPath, "User")
# 5. 基础 NPM 加速配置 (设置镜像站和超长超时)
Write-Host ">>> 正在配置 NPM 基础加速..." -ForegroundColor Yellow
& cmd /c "npm config set registry https://registry.npmmirror.com"
& cmd /c "npm config set fetch-retry-maxtimeout 600000"
& cmd /c "npm config set fetch-timeout 600000"
Write-Host "------------------------------------------------" -ForegroundColor Cyan
Write-Host ">>> 配置已全线打通!请【重启 PowerShell】后生效 <<<" -ForegroundColor Greennode -v
npm -v
原创文章,作者:开心电脑网,如若转载,请注明出处。