Node.js完整安装配置指南(包含国内镜像配置)

Node.js完整安装配置指南(包含国内镜像配置)

一、Node.js安装

方法1:使用Chocolatey安装(推荐)

powershell 复制代码
# 安装最新LTS版本
choco install nodejs

# 或安装指定版本
choco install nodejs --version=20.11.0

方法2:官网下载安装

  1. 访问 Node.js官网
  2. 下载LTS版本(推荐)
  3. 运行安装程序,勾选"Add to PATH"选项

方法3:使用国内镜像下载

powershell 复制代码
# 从淘宝镜像下载
# 访问: https://npmmirror.com/mirrors/node/
# 选择对应版本下载

二、验证安装

powershell 复制代码
# 检查Node.js版本
node --version
# 或
node -v

# 检查npm版本
npm --version
# 或
npm -v

三、国内镜像源配置

3.1 淘宝镜像(npmmirror)

powershell 复制代码
# 设置淘宝镜像
npm config set registry https://registry.npmmirror.com

# 验证配置
npm config get registry

3.2 中科大镜像

powershell 复制代码
# 设置中科大镜像
npm config set registry https://npmreg.proxy.ustclug.org/

# 验证配置
npm config get registry

3.3 清华大学镜像

powershell 复制代码
# 设置清华镜像
npm config set registry https://mirrors.tuna.tsinghua.edu.cn/npm/

# 验证配置
npm config get registry

3.4 华为云镜像

powershell 复制代码
# 设置华为云镜像
npm config set registry https://mirrors.huaweicloud.com/repository/npm/

# 验证配置
npm config get registry

3.5 腾讯云镜像

powershell 复制代码
# 设置腾讯云镜像
npm config set registry https://mirrors.cloud.tencent.com/npm/

# 验证配置
npm config get registry

四、镜像切换脚本

4.1 创建镜像切换批处理文件

创建文件 npm_registry_switch.bat

batch 复制代码
@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

powershell 复制代码
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 检查现有环境变量

powershell 复制代码
# 检查PATH中是否包含Node.js
echo $env:PATH | Select-String "node"

# 或在CMD中
echo %PATH% | findstr node

5.2 手动配置环境变量

如果Node.js没有自动添加到PATH,需要手动添加:

  1. 通过系统设置配置:

    • Win + R,输入 sysdm.cpl
    • 点击"高级"选项卡 → "环境变量"
    • 在"系统变量"中找到"Path",点击"编辑"
    • 添加Node.js安装路径(通常是 C:\Program Files\nodejs\
  2. 通过PowerShell配置:

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全局模块路径

powershell 复制代码
# 查看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配置

powershell 复制代码
# 设置镜像源(选择一个)
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 proxy http://proxy.company.com:8080
# npm config set https-proxy http://proxy.company.com:8080

# 设置严格SSL(建议保持true)
npm config set strict-ssl true

# 设置日志级别
npm config set loglevel warn

# 设置进度条显示
npm config set progress true

6.2 查看和重置配置

powershell 复制代码
# 查看所有配置
npm config list

# 查看完整配置(包括默认值)
npm config list -l

# 重置到默认配置
npm config delete registry
npm config delete cache
npm config delete prefix

# 或直接编辑配置文件
npm config edit

七、常用镜像测速脚本

创建文件 npm_speed_test.js

javascript 复制代码
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();

运行测试:

powershell 复制代码
node npm_speed_test.js

八、使用nrm管理镜像源

8.1 安装nrm

powershell 复制代码
# 全局安装nrm
npm install -g nrm

8.2 使用nrm

powershell 复制代码
# 列出可用镜像源
nrm ls

# 测试所有镜像源速度
nrm test

# 切换到指定镜像源
nrm use taobao

# 添加自定义镜像源
nrm add custom https://your-registry.com/

# 删除镜像源
nrm del custom

# 查看当前镜像源
nrm current

九、故障排除

9.1 常见问题及解决方案

问题1:npm命令不被识别

powershell 复制代码
# 解决方案:重新添加环境变量
refreshenv  # 如果使用Chocolatey
# 或重启命令行/PowerShell

问题2:权限错误

powershell 复制代码
# 解决方案:以管理员身份运行
# 或配置npm使用不同的目录
npm config set prefix "C:\Users\%USERNAME%\AppData\Roaming\npm"

问题3:网络连接问题

powershell 复制代码
# 解决方案:切换镜像源
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 清理和重置

powershell 复制代码
# 清理npm缓存
npm cache clean --force

# 清理node_modules
rm -rf node_modules
rm package-lock.json
npm install

# 重置npm配置
npm config delete registry
npm config delete proxy
npm config delete https-proxy

十、验证安装和配置

powershell 复制代码
# 最终验证命令
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)"

十一、推荐的完整配置命令

powershell 复制代码
# 一键配置脚本(推荐配置)
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配置完成!"

注意事项:

  1. 优先推荐使用淘宝镜像(npmmirror),稳定性和速度都比较好
  2. 如果在企业环境,可能需要配置代理
  3. 定期运行 npm update -g 更新全局包
  4. 建议使用Node.js LTS版本以确保稳定性

🚀 快速开始(推荐步骤)

  1. 安装Node.js
powershell 复制代码
choco install nodejs
  1. 配置淘宝镜像(最稳定):
powershell 复制代码
npm config set registry https://registry.npmmirror.com
  1. 验证安装
powershell 复制代码
node --version
npm --version
npm config get registry

🔧 解决PowerShell执行策略问题

方法1:修改PowerShell执行策略(推荐)

powershell 复制代码
# 以管理员身份运行PowerShell,然后执行:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

# 或者更宽松的策略:
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope CurrentUser

方法2:使用CMD而不是PowerShell

cmd 复制代码
# 打开CMD(命令提示符)而不是PowerShell
# 按Win+R,输入cmd,然后运行npm命令

npm --version
npm config set registry https://registry.npmmirror.com

方法3:刷新环境变量

powershell 复制代码
# 在PowerShell中刷新环境变量
refreshenv

# 然后再试npm命令

方法4:使用完整路径

powershell 复制代码
# 直接使用npm.cmd而不是npm.ps1
& "C:\Program Files\nodejs\npm.cmd" --version
& "C:\Program Files\nodejs\npm.cmd" config set registry https://registry.npmmirror.com

🚀 完整解决步骤## 🎯 立即解决方案

您的Node.js安装成功了!现在遇到的是PowerShell执行策略问题。有3个快速解决方案:

方案1:使用CMD(最简单)

cmd 复制代码
# 按 Win+R,输入 cmd,回车打开CMD
npm --version
npm config set registry https://registry.npmmirror.com
npm config get registry

方案2:在PowerShell中修改执行策略

powershell 复制代码
# 在当前PowerShell中执行:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
# 然后就可以正常使用npm了

方案3:在PowerShell中使用npm.cmd

powershell 复制代码
# 使用npm.cmd而不是npm
npm.cmd --version
npm.cmd config set registry https://registry.npmmirror.com
npm.cmd config get registry

🚀 推荐立即执行

我建议您现在就用方案1(CMD),因为最简单快速:

  1. 打开CMD :按 Win+R → 输入 cmd → 回车
  2. 执行配置
cmd 复制代码
npm --version
npm config set registry https://registry.npmmirror.com
npm config set cache "C:\Users\Administrator\.npm" 
npm config set prefix "C:\Users\Administrator\AppData\Roaming\npm"
npm config list
  1. 测试安装
cmd 复制代码
npm install -g npm@latest

解决npm PowerShell执行策略问题

问题描述

Node.js安装成功,但在PowerShell中运行npm命令时出现执行策略错误:

复制代码
npm : 无法加载文件 D:\Program Files\nodejs\npm.ps1,因为在此系统上禁止运行脚本

解决方案

方案1:修改PowerShell执行策略(推荐)

步骤1:以管理员身份打开PowerShell
powershell 复制代码
# 右键点击开始菜单 → Windows PowerShell (管理员)
步骤2:检查当前执行策略
powershell 复制代码
Get-ExecutionPolicy
步骤3:修改执行策略
powershell 复制代码
# 选择以下任一命令:

# 选项A:仅允许本地脚本和已签名的远程脚本(推荐)
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

# 选项B:允许所有脚本(如果A不行)
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope CurrentUser

# 选项C:系统级设置(需要管理员权限)
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine
步骤4:验证修改
powershell 复制代码
Get-ExecutionPolicy
npm --version

方案2:使用CMD(立即可用)

步骤1:打开CMD
cmd 复制代码
# 按 Win + R,输入 cmd,按回车
步骤2:测试npm
cmd 复制代码
npm --version
npm config set registry https://registry.npmmirror.com
npm config get registry

方案3:在PowerShell中使用.cmd文件

powershell 复制代码
# 直接调用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别名

powershell 复制代码
# 在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

batch 复制代码
@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一键修复脚本

powershell 复制代码
# 保存为 Fix-NpmPowerShell.ps1
Write-Host "正在修复npm PowerShell执行策略问题..." -ForegroundColor Green

# 检查当前执行策略
$currentPolicy = Get-ExecutionPolicy
Write-Host "当前执行策略: $currentPolicy" -ForegroundColor Yellow

# 如果是Restricted,则修改
if ($currentPolicy -eq "Restricted") {
    try {
        Set-ExecutionPolicy -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
}

# 测试npm
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中执行(最稳定):

cmd 复制代码
REM 1. 验证安装
node --version
npm --version

REM 2. 配置淘宝镜像
npm config set registry https://registry.npmmirror.com

REM 3. 配置其他设置
npm config set cache "C:\Users\%USERNAME%\.npm"
npm config set prefix "C:\Users\%USERNAME%\AppData\Roaming\npm"

REM 4. 验证配置
npm config list

REM 5. 测试安装包
npm install -g npm@latest

或在PowerShell中使用.cmd版本:

powershell 复制代码
# 1. 验证安装
node --version
npm.cmd --version

# 2. 配置镜像
npm.cmd config set registry https://registry.npmmirror.com

# 3. 验证配置
npm.cmd config get registry

故障排除

如果仍然有问题:

  1. 重启命令行工具

  2. 检查环境变量

    powershell 复制代码
    $env:PATH -split ';' | Where-Object { $_ -like "*node*" }
  3. 手动添加到PATH

    powershell 复制代码
    $env:PATH += ";C:\Program Files\nodejs\"
  4. 使用完整路径

    powershell 复制代码
    & "C:\Program Files\nodejs\npm.cmd" --version

总结

最简单的解决方案:

  1. 使用CMD而不是PowerShell进行npm操作
  2. 或者在PowerShell中使用 npm.cmd 而不是 npm
  3. 长期解决:修改PowerShell执行策略