一、前置基础——02-开发环境搭建/01-Node.js安装与版本管理
本文介绍了Node.js的安装与版本管理方法。主要内容包括:1) Node.js版本策略(LTS长期支持版与Current最新特性版);2) Windows、macOS和Linux三大平台的安装指南;3) 推荐使用nvm、n和fnm等版本管理工具进行多版本切换;4) npm配置优化技巧,包括镜像源设置和全局路径配置;5) 安装验证方法与常见问题解决方案。文章特别强调了生产环境应使用LTS版本,并提
·

02-开发环境搭建/01-Node.js安装与版本管理
Node.js 安装与版本管理
学习目标
- 掌握在不同操作系统上安装 Node.js 的方法
- 学会使用 nvm 管理多个 Node.js 版本
- 理解 Node.js 版本策略(LTS vs Current)
- 配置 npm 全局模块路径
前置知识
- 基本的命令行操作
- 文件系统基础概念
知识点列表
1. Node.js 版本介绍
1.1 版本号规则
- 语义化版本:major.minor.patch
- major:不兼容的 API 变更
- minor:向后兼容的功能新增
- patch:向后兼容的问题修复
1.2 LTS vs Current
-
LTS(Long Term Support):长期支持版本
- 适合生产环境
- 维护周期30个月
- 偶数版本号(如14.x、16.x、18.x)
-
Current:当前最新版本
- 适合开发测试
- 包含最新特性
- 奇数版本号(如15.x、17.x、19.x)
# 查看当前 Node.js 版本
node --version
# 或
node -v
# 查看 npm 版本
npm --version
npm -v
2. 各平台安装方法
2.1 Windows 安装
2.1.1 官方安装包(推荐新手)
- 访问 https://nodejs.org
- 下载 LTS 版本 .msi 安装包
- 运行安装程序,一路 Next
- 验证安装:
node --version
npm --version
2.1.2 使用 Chocolatey(包管理器)
# 安装 LTS 版本
choco install nodejs-lts
# 安装 Current 版本
choco install nodejs
2.2 macOS 安装
2.2.1 官方安装包(推荐新手)
- 访问 https://nodejs.org
- 下载 .pkg 安装包
- 运行安装程序
2.2.2 使用 Homebrew(推荐开发者)
# 安装 Homebrew(如未安装)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# 安装 Node.js
brew install node
# 安装 LTS 版本
brew install node@18
# 切换版本
brew link --overwrite node@18
2.3 Linux 安装
2.3.1 Ubuntu/Debian
# 使用 NodeSource 官方源
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
# 安装开发工具(编译原生模块)
sudo apt-get install -y build-essential
2.3.2 CentOS/RHEL
# 使用 NodeSource 官方源
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs
# 安装开发工具
sudo yum install -y gcc-c++ make
3. 版本管理工具(推荐)
3.1 nvm(Node Version Manager)- 最流行
3.1.1 安装 nvm
# macOS/Linux
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# 或者使用 wget
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# 重启终端或执行
source ~/.bashrc # 或 source ~/.zshrc
# Windows 使用 nvm-windows
# 下载地址:https://github.com/coreybutler/nvm-windows/releases
3.1.2 nvm 常用命令
# 查看已安装版本
nvm list
# 查看可远程安装的版本
nvm list available
nvm ls-remote
# 安装指定版本
nvm install 18.17.0 # 安装特定版本
nvm install 18 # 安装最新 18.x
nvm install node # 安装最新 Current
# 切换版本
nvm use 18.17.0 # 当前会话切换
nvm alias default 18.17.0 # 设置默认版本
# 卸载版本
nvm uninstall 16.20.0
# 查看当前版本
nvm current
# 执行命令使用指定版本
nvm exec 14.21.0 node app.js
3.2 n(简单易用)
# 安装 n(需要先有 Node.js)
npm install -g n
# 安装 LTS 版本
n lts
# 安装最新版本
n latest
# 安装指定版本
n 18.17.0
# 切换版本
n
# 删除版本
n rm 16.20.0
3.3 fnm(快速版本管理器 - Rust 编写)
# macOS/Linux 安装
curl -fsSL https://fnm.vercel.app/install | bash
# 使用
fnm list-remote # 查看可用版本
fnm install 18.17.0 # 安装版本
fnm use 18.17.0 # 使用版本
fnm default 18.17.0 # 设置默认
4. npm 配置优化
4.1 配置全局安装路径
# 查看当前配置
npm config list
# 设置全局模块安装路径
npm config set prefix "~/.npm-global"
# 添加到 PATH(在 ~/.bashrc 或 ~/.zshrc)
export PATH=~/.npm-global/bin:$PATH
# 重新加载配置
source ~/.bashrc
4.2 配置镜像源
# 查看当前源
npm config get registry
# 切换到淘宝镜像
npm config set registry https://registry.npmmirror.com
# 切换回官方源
npm config set registry https://registry.npmjs.org
# 使用 cnpm
npm install -g cnpm --registry=https://registry.npmmirror.com
# 使用 nrm 管理源
npm install -g nrm
nrm ls # 列出所有源
nrm use taobao # 切换源
nrm test # 测试速度
4.3 配置代理
# 设置代理
npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080
# 取消代理
npm config delete proxy
npm config delete https-proxy
# 设置 strict-ssl(内部证书问题)
npm config set strict-ssl false
5. 验证安装
5.1 基础验证
# 检查 Node.js 版本
node -v
# 检查 npm 版本
npm -v
# 检查 npx 版本
npx -v
# 查看 Node.js 路径
which node
# 查看 npm 全局路径
npm root -g
5.2 运行测试脚本
// test.js
console.log('Node.js 版本:', process.version);
console.log('当前平台:', process.platform);
console.log('当前目录:', process.cwd());
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello Node.js!');
});
server.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
# 运行测试
node test.js
# 浏览器访问 http://localhost:3000
# Ctrl+C 停止服务器
6. 常见问题解决
6.1 权限问题
# EACCES 权限错误
# 方法1:修复 npm 权限
sudo chown -R $(whoami) ~/.npm
# 方法2:使用 nvm 避免权限问题
# 方法3:修改全局目录
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
6.2 环境变量问题
# macOS/Linux - 添加到 ~/.bashrc 或 ~/.zshrc
export PATH=/usr/local/bin:$PATH
export NODE_PATH=/usr/local/lib/node_modules
# Windows - 系统属性 > 环境变量
# 添加 NODE_PATH=C:\Users\用户名\AppData\Roaming\npm\node_modules
6.3 版本冲突
# 清理 npm 缓存
npm cache clean --force
# 删除 node_modules 重装
rm -rf node_modules
npm install
# 使用 nvm 切换版本
nvm use 18
代码示例
示例1:版本检查脚本
// version-check.js
const os = require('os');
console.log('========== Node.js 环境信息 ==========');
console.log(`Node.js 版本: ${process.version}`);
console.log(`npm 版本: ${require('child_process').execSync('npm -v').toString().trim()}`);
console.log(`操作系统: ${os.platform()} ${os.arch()}`);
console.log(`当前用户: ${os.userInfo().username}`);
console.log(`CPU 核心数: ${os.cpus().length}`);
console.log(`总内存: ${(os.totalmem() / 1024 / 1024 / 1024).toFixed(2)} GB`);
console.log('======================================');
// 检查必要工具
const tools = ['node', 'npm', 'npx'];
tools.forEach(tool => {
try {
const version = require('child_process').execSync(`${tool} -v`).toString().trim();
console.log(`${tool}: ${version}`);
} catch (e) {
console.log(`${tool}: 未安装`);
}
});
示例2:环境配置脚本
// setup-env.js
const fs = require('fs');
const path = require('path');
const os = require('os');
function checkNodeEnvironment() {
const results = {
node: process.version,
npm: null,
platform: os.platform(),
arch: os.arch(),
envPaths: {
nodePath: process.env.NODE_PATH || '未设置',
npmPrefix: null,
npmCache: null
}
};
try {
results.npm = require('child_process').execSync('npm -v').toString().trim();
results.envPaths.npmPrefix = require('child_process')
.execSync('npm config get prefix').toString().trim();
results.envPaths.npmCache = require('child_process')
.execSync('npm config get cache').toString().trim();
} catch (e) {
results.npm = '无法获取';
}
return results;
}
function generateEnvFile() {
const envContent = `
# Node.js 环境配置
NODE_VERSION=${process.version}
NPM_VERSION=${require('child_process').execSync('npm -v').toString().trim()}
NODE_ENV=development
# 路径配置
NODE_PATH=${path.join(os.homedir(), '.npm-global', 'lib', 'node_modules')}
# 镜像源(可选)
# npm config set registry https://registry.npmmirror.com
`.trim();
const envPath = path.join(process.cwd(), '.env.example');
fs.writeFileSync(envPath, envContent);
console.log(`已生成环境配置文件: ${envPath}`);
}
// 执行
console.log(checkNodeEnvironment());
generateEnvFile();
练习题
基础题
- 使用 nvm 安装 Node.js 18.x 和 20.x 两个版本,并切换使用
- 配置 npm 使用淘宝镜像源,安装一个全局包测试
- 编写一个脚本,输出当前 Node.js 的安装路径和全局模块路径
进阶题
- 创建一个 shell 脚本,自动检测并安装合适的 Node.js 版本
- 配置多个项目使用不同的 Node.js 版本,实现自动切换
练习题参考答案
基础题1 - 使用 nvm
# 安装版本
nvm install 18
nvm install 20
# 查看已安装
nvm list
# 切换版本
nvm use 18
node -v # 验证
nvm use 20
node -v # 验证
# 设置默认
nvm alias default 18
基础题2 - 配置镜像
# 配置淘宝镜像
npm config set registry https://registry.npmmirror.com
# 验证配置
npm config get registry
# 安装全局包测试
npm install -g nodemon
# 恢复官方源
npm config set registry https://registry.npmjs.org
基础题3 - 路径检查脚本
const path = require('path');
const { execSync } = require('child_process');
console.log('Node.js 路径:', process.execPath);
console.log('npm 全局模块路径:', execSync('npm root -g').toString().trim());
console.log('npm 缓存路径:', execSync('npm config get cache').toString().trim());
console.log('当前 PATH:', process.env.PATH);
openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构
更多推荐
所有评论(0)