跳到主要内容JavaScriptNode.js大前端
Node.js 完整安装配置指南(含国内镜像配置)
综述由AI生成档详细介绍了 Node.js 的完整安装与配置流程。涵盖 Chocolatey、官网及国内镜像三种安装方式,以及 Node.js 和 npm 版本的验证方法。重点讲解了国内主流镜像源(淘宝、中科大、清华等)的配置与切换,包括批处理和 PowerShell 脚本工具。内容还涉及环境变量配置、npm 全局模块路径设置、缓存管理及 nrm 工具的使用。针对常见的 PowerShell 执行策略导致 npm 无法运行的问题,提供了多种解决方案,包括修改执行策略、使用 CMD 替代、调用 npm.cmd 及创建别名等。最后包含测速脚本、故障排除步骤及推荐的一键配置命令,帮助用户快速搭建稳定的开发环境。
樱花落尽19 浏览 Node.js 完整安装配置指南
一、Node.js 安装
方法 1:使用 Chocolatey 安装(推荐)
choco install nodejs
choco install nodejs --version=20.11.0
方法 2:官网下载安装
- 访问 Node.js 官网
- 下载 LTS 版本(推荐)
- 运行安装程序,勾选 "Add to PATH" 选项
方法 3:使用国内镜像下载
二、验证安装
node --version
npm --version
三、国内镜像源配置
3.1 淘宝镜像(npmmirror)
npm config set registry https://registry.npmmirror.com
npm config get registry
3.2 中科大镜像
npm config set registry https://npmreg.proxy.ustclug.org/
npm config get registry
3.3 清华大学镜像
npm config set registry https://mirrors.tuna.tsinghua.edu.cn/npm/
npm config get registry
3.4 华为云镜像
npm config set registry https://mirrors.huaweicloud.com/repository/npm/
npm config get registry
3.5 腾讯云镜像
npm config set registry https://mirrors.cloud.tencent.com/npm/
npm config get registry
四、镜像切换脚本
4.1 创建镜像切换批处理文件
创建文件 :
npm_registry_switch.bat
@echo off
echo 选择 npm 镜像源:
echo 1. 官方源 (默认)
echo 2. 淘宝镜像 (npmmirror)
echo 3. 中科大镜像
echo 4. 清华大学镜像
echo 5. 华为云镜像
echo 6. 腾讯云镜像
echo 7. 查看当前镜像源
echo.
set /p choice=请输入选择 (1-7):
if "%choice%"=="1" (
npm config set registry https://registry.npmjs.org/
echo 已切换到官方源
) else if "%choice%"=="2" (
npm config set registry https://registry.npmmirror.com
echo 已切换到淘宝镜像
) else if "%choice%"=="3" (
npm config set registry https://npmreg.proxy.ustclug.org/
echo 已切换到中科大镜像
) else if "%choice%"=="4" (
npm config set registry https://mirrors.tuna.tsinghua.edu.cn/npm/
echo 已切换到清华大学镜像
) else if "%choice%"=="5" (
npm config set registry https://mirrors.huaweicloud.com/repository/npm/
echo 已切换到华为云镜像
) else if "%choice%"=="6" (
npm config set registry https://mirrors.cloud.tencent.com/npm/
echo 已切换到腾讯云镜像
) else if "%choice%"=="7" (
echo 当前镜像源:
npm config get registry
) else (
echo 无效选择
)
echo.
echo 当前配置:
npm config get registry
pause
4.2 PowerShell 版本切换脚本
创建文件 Switch-NpmRegistry.ps1:
function Switch-NpmRegistry {
param([Parameter(Mandatory=$false)][string]$Registry)
$registries = @{
"npm" = "https://registry.npmjs.org/"
"taobao" = "https://registry.npmmirror.com"
"ustc" = "https://npmreg.proxy.ustclug.org/"
"tsinghua" = "https://mirrors.tuna.tsinghua.edu.cn/npm/"
"huawei" = "https://mirrors.huaweicloud.com/repository/npm/"
"tencent" = "https://mirrors.cloud.tencent.com/npm/"
}
if (-not $Registry) {
Write-Host "可用的镜像源:" -ForegroundColor Green
$registries.GetEnumerator() | ForEach-Object {
Write-Host " $($_.Key): $($_.Value)" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "当前镜像源:$(npm config get registry)" -ForegroundColor Cyan
return
}
if ($registries.ContainsKey($Registry.ToLower())) {
$url = $registries[$Registry.ToLower()]
npm config set registry $url
Write-Host "已切换到 $Registry 镜像:$url" -ForegroundColor Green
} else {
Write-Host "未知的镜像源:$Registry" -ForegroundColor Red
Write-Host "可用选项:$($registries.Keys -join', ')" -ForegroundColor Yellow
}
}
# 使用示例:
# Switch-NpmRegistry taobao # 切换到淘宝镜像
# Switch-NpmRegistry # 显示所有可用镜像
五、环境变量配置
5.1 检查现有环境变量
echo $env:PATH | Select-String "node"
echo %PATH% | findstr node
5.2 手动配置环境变量
如果 Node.js 没有自动添加到 PATH,需要手动添加:
- 通过系统设置配置:
- 按
Win + R,输入 sysdm.cpl
- 点击 "高级" 选项卡 → '环境变量'
- 在 "系统变量" 中找到 "Path",点击 "编辑"
- 添加 Node.js 安装路径(通常是
C:\Program Files\nodejs\)
- 通过 PowerShell 配置:
# 临时添加到当前会话
$env:PATH += ";C:\Program Files\nodejs\"
# 永久添加到用户环境变量
[Environment]::SetEnvironmentVariable("PATH", $env:PATH + ";C:\Program Files\nodejs\", "User")
# 永久添加到系统环境变量(需要管理员权限)
[Environment]::SetEnvironmentVariable("PATH", $env:PATH + ";C:\Program Files\nodejs\", "Machine")
5.3 配置 npm 全局模块路径
npm config list
npm config set prefix "C:\Users\%USERNAME%\AppData\Roaming\npm"
npm config set prefix "D:\nodejs\npm-global"
六、npm 配置优化
6.1 完整的 npm 配置
npm config set registry https://registry.npmmirror.com
npm config set cache "D:\nodejs\npm-cache"
npm config set prefix "D:\nodejs\npm-global"
npm config set strict-ssl true
npm config set loglevel warn
npm config set progress true
6.2 查看和重置配置
npm config list
npm config list -l
npm config delete registry
npm config delete cache
npm config delete prefix
npm config edit
七、常用镜像测速脚本
const { execSync } = require('child_process');
const registries = {
'npm 官方源': 'https://registry.npmjs.org/',
'淘宝镜像': 'https://registry.npmmirror.com',
'中科大镜像': 'https://npmreg.proxy.ustclug.org/',
'清华镜像': 'https://mirrors.tuna.tsinghua.edu.cn/npm/',
'华为云镜像': 'https://mirrors.huaweicloud.com/repository/npm/',
'腾讯云镜像': 'https://mirrors.cloud.tencent.com/npm/'
};
async function testSpeed(name, url) {
try {
const start = Date.now();
execSync(`npm ping --registry ${url}`, { stdio: 'pipe', timeout: 10000 });
const end = Date.now();
return end - start;
} catch (error) {
return Infinity;
}
}
async function testAllRegistries() {
console.log('正在测试各镜像源速度...\n');
const results = [];
for (const [name, url] of Object.entries(registries)) {
process.stdout.write(`测试 ${name}... `);
const time = await testSpeed(name, url);
if (time === Infinity) {
console.log('❌ 超时或失败');
results.push({ name, url, time: Infinity, status: 'failed' });
} else {
console.log(`✅ ${time}ms`);
results.push({ name, url, time, status: 'success' });
}
}
results.sort((a, b) => a.time - b.time);
console.log('\n=== 测试结果(按速度排序)===');
results.forEach((result, index) => {
if (result.status === 'success') {
console.log(`${index + 1}. ${result.name}: ${result.time}ms`);
console.log(`${result.url}`);
}
});
console.log('\n推荐使用最快的镜像源。');
if (results[0].status === 'success') {
console.log(`\n执行以下命令切换到最快的镜像源:`);
console.log(`npm config set registry ${results[0].url}`);
}
}
testAllRegistries();
八、使用 nrm 管理镜像源
8.1 安装 nrm
8.2 使用 nrm
nrm ls
nrm test
nrm use taobao
nrm add custom https://your-registry.com/
nrm del custom
nrm current
九、故障排除
9.1 常见问题及解决方案
npm config set prefix "C:\Users\%USERNAME%\AppData\Roaming\npm"
npm config set registry https://registry.npmmirror.com
npm config set proxy http://your-proxy:port
npm config set https-proxy http://your-proxy:port
9.2 清理和重置
npm cache clean --force
rm -rf node_modules
rm package-lock.json
npm install
npm config delete registry
npm config delete proxy
npm config delete https-proxy
十、验证安装和配置
node --version
npm --version
npm config get registry
npm config get prefix
npm install -g npm@latest
mkdir test-node
cd test-node
npm init -y
npm install lodash
node -e "console.log(require('lodash').VERSION)"
十一、推荐的完整配置命令
npm config set registry https://registry.npmmirror.com
npm config set cache "C:\Users\%USERNAME%\.npm"
npm config set prefix "C:\Users\%USERNAME%\AppData\Roaming\npm"
npm config set progress true
npm config set loglevel warn
npm config list
echo "Node.js 和 npm 配置完成!"
注意事项
- 优先推荐使用淘宝镜像(npmmirror),稳定性和速度都比较好
- 如果在企业环境,可能需要配置代理
- 定期运行
npm update -g 更新全局包
- 建议使用 Node.js LTS 版本以确保稳定性
十二、解决 PowerShell 执行策略问题
Node.js 安装成功,但在 PowerShell 中运行 npm 命令时可能出现执行策略错误:
npm : 无法加载文件 D:\Program Files\nodejs\npm.ps1,因为在此系统上禁止运行脚本
方案 1:修改 PowerShell 执行策略(推荐)
- 以管理员身份打开 PowerShell
- 检查当前执行策略:
Get-ExecutionPolicy
- 修改执行策略:
# 选项 A:仅允许本地脚本和已签名的远程脚本(推荐)
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
# 选项 B:允许所有脚本(如果 A 不行)
Set-ExecutionPolicy Bypass -Scope CurrentUser
# 选项 C:系统级设置(需要管理员权限)
Set-ExecutionPolicy RemoteSigned -Scope LocalMachine
- 验证修改:
Get-ExecutionPolicy 和 npm --version
方案 2:使用 CMD(立即可用)
- 打开 CMD(按 Win+R,输入 cmd,回车)
- 测试 npm:
npm --version
npm config set registry https://registry.npmmirror.com
npm config get registry
方案 3:在 PowerShell 中使用 .cmd 文件
直接调用 npm.cmd 而不是 npm.ps1:
& "npm.cmd" --version
& "npm.cmd" config set registry https://registry.npmmirror.com
# 或者使用完整路径
& "C:\Program Files\nodejs\npm.cmd" --version
方案 4:创建 PowerShell 别名
if (!(Test-Path -Path $PROFILE)) {
New-Item -ItemType File -Path $PROFILE -Force
}
Add-Content -Path $PROFILE -Value 'function npm { & "npm.cmd" @args }'
Add-Content -Path $PROFILE -Value 'function npx { & "npx.cmd" @args }'
# 重新加载配置
.$PROFILE
快速验证脚本
创建测试脚本 test_npm.bat
@echo off
echo ========== Node.js 和 npm 测试 ==========
echo.
echo 1. 检查 Node.js 版本:
node --version
echo.
echo 2. 检查 npm 版本:
npm.cmd --version
echo.
echo 3. 设置淘宝镜像:
npm.cmd config set registry https://registry.npmmirror.com
echo.
echo 4. 验证镜像设置:
npm.cmd config get registry
echo.
echo 5. 测试 npm 安装(安装一个小包):
npm.cmd install -g npm@latest
echo.
echo ========== 测试完成 ==========
pause
PowerShell 一键修复脚本
保存为 Fix-NpmPowerShell.ps1:
Write-Host "正在修复 npm PowerShell 执行策略问题..." -ForegroundColor Green
$currentPolicy = Get-ExecutionPolicy
Write-Host "当前执行策略:$currentPolicy" -ForegroundColor Yellow
if ($currentPolicy -eq "Restricted") {
try {
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
Write-Host "✅ 执行策略已修改为 RemoteSigned" -ForegroundColor Green
} catch {
Write-Host "❌ 修改执行策略失败,请以管理员身份运行" -ForegroundColor Red
Write-Host "手动执行:Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser" -ForegroundColor Yellow
}
}
if (Get-Command refreshenv -ErrorAction SilentlyContinue) {
refreshenv
Write-Host "✅ 环境变量已刷新" -ForegroundColor Green
}
Write-Host "`n 正在测试 npm..." -ForegroundColor Cyan
try {
$nodeVersion = node --version
Write-Host "Node.js 版本:$nodeVersion" -ForegroundColor Green
$npmVersion = npm --version
Write-Host "npm 版本:$npmVersion" -ForegroundColor Green
Write-Host "✅ npm 工作正常!" -ForegroundColor Green
} catch {
Write-Host "⚠️ npm 仍有问题,建议使用 CMD 或 npm.cmd" -ForegroundColor Yellow
Write-Host "备用方案:使用 'npm.cmd' 而不是 'npm'" -ForegroundColor Yellow
}
Write-Host "`n 修复完成!" -ForegroundColor Green
总结
- 使用 CMD 而不是 PowerShell 进行 npm 操作
- 或者在 PowerShell 中使用
npm.cmd 而不是 npm
- 长期解决:修改 PowerShell 执行策略
相关免费在线工具
- Keycode 信息
查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
- Escape 与 Native 编解码
JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
- JavaScript / HTML 格式化
使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
- JavaScript 压缩与混淆
Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
- Base64 字符串编码/解码
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
- Base64 文件转换器
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online