适合:开发环境快速搭建 / 服务器部署 / 学习 Node.js
关键词:Node.js 安装、npm 安装、一行命令、Debian、Ubuntu、CentOS、Arch、macOS、Windows
一、为什么要"一条命令"安装 Node.js?
在实际开发或实验环境中,我们经常遇到这些情况:
- 新服务器 / 新虚拟机,需要 快速部署环境
- 临时测试项目,不想写复杂脚本
- 教学、实验、Docker、CI/CD 场景
- 想要 复制即用,减少出错概率
因此,"一条命令完成 Node.js + npm 安装"非常实用。
二、统一说明(非常重要)
- 默认安装 Node.js 20(LTS)
- npm 会随 Node.js 自动安装
- 使用 官方推荐方式
- 所有命令都可直接复制运行
⚠️ 注意:
文中部分命令使用了 curl | bash,这是 NodeSource / 官方工具推荐方案,生产环境可先下载脚本查看后再执行。
三、Debian / Ubuntu 一条命令安装 Node.js + npm(推荐)
适用于:
- Debian 10 / 11 / 12
- Ubuntu 18.04 / 20.04 / 22.04 / 24.04
bash
sudo apt update -y && sudo apt install -y curl ca-certificates gnupg && curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - && sudo apt install -y nodejs && node -v && npm -v
执行完成后会输出类似:
text
v20.x.x
10.x.x
说明安装成功 ✅
四、CentOS / Rocky / AlmaLinux 一条命令
1️⃣ CentOS 7 / 8(yum)
bash
sudo yum install -y curl && curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash - && sudo yum install -y nodejs && node -v && npm -v
2️⃣ Rocky Linux / AlmaLinux / 新系统(dnf)
bash
sudo dnf install -y curl && curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash - && sudo dnf install -y nodejs && node -v && npm -v
五、Fedora 一条命令
bash
sudo dnf install -y curl && curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash - && sudo dnf install -y nodejs && node -v && npm -v
六、Arch Linux / Manjaro(最简单)
Arch 官方仓库本身就很新:
bash
sudo pacman -Syu --noconfirm nodejs npm && node -v && npm -v
七、openSUSE 一条命令
bash
sudo zypper install -y curl && curl -fsSL https://rpm.nodesource.com/setup_20.x | sudo bash - && sudo zypper install -y nodejs && node -v && npm -v
八、macOS 一条命令(Homebrew)
1️⃣ 如果 没有安装 Homebrew
bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" && brew install node && node -v && npm -v
2️⃣ 如果 已经安装 Homebrew
bash
brew install node && node -v && npm -v
九、Windows 一条命令(PowerShell)
推荐方式:winget
powershell
winget install OpenJS.NodeJS.LTS -e --source winget
安装完成后重新打开终端:
powershell
node -v
npm -v
十、真正的"跨平台万能一行"(强烈推荐开发者)
使用 nvm(Node Version Manager)
适合:开发机 / 教学 / 多版本测试
Linux / macOS:
bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash && source ~/.bashrc && nvm install --lts && node -v && npm -v
优点:
- 不需要 sudo
- 支持多版本 Node
- 不污染系统环境
- 适合长期开发
十一、常见问题总结
❓ npm 权限错误(EACCES)
bash
sudo chown -R $USER:$USER ~/.npm
或直接使用 nvm(推荐)。
❓ node / npm 找不到命令
bash
which node
which npm
如果没有路径,说明环境变量未生效,重新打开终端即可。
十二、总结
| 场景 | 推荐方案 |
|---|---|
| 服务器部署 | NodeSource 一行命令 |
| 本地开发 | nvm 一行命令 |
| Arch 系 | pacman |
| macOS | Homebrew |
| Windows | winget |
一句话总结:
复制 → 粘贴 → 回车 → Node.js 环境就绪