温馨提示×

Debian怎样配置Nodejs环境

小樊
35
2026-07-29 12:46:39
栏目: 编程语言

在 Debian 系统上配置 Node.js 环境,常见且推荐的方式有以下几种。下面按推荐程度从高到低说明,并给出完整步骤。


✅ 方法一(推荐):使用 NodeSource 安装最新 LTS 版本

适合需要较新 Node.js 的用户(开发环境、生产环境均适用)。

1️⃣ 更新系统

sudo apt update
sudo apt upgrade -y

2️⃣ 安装必要依赖

sudo apt install -y curl ca-certificates gnupg

3️⃣ 导入 NodeSource GPG 密钥

curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /usr/share/keyrings/nodesource.gpg

4️⃣ 添加 NodeSource 仓库(以 Node.js 20 LTS 为例)

NODE_MAJOR=20
echo "deb [signed-by=/usr/share/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list

5️⃣ 安装 Node.js

sudo apt update
sudo apt install -y nodejs

6️⃣ 验证安装

node -v
npm -v

✅ 方法二:使用 Debian 官方仓库(简单但版本较旧)

适合对版本要求不高的场景。

sudo apt update
sudo apt install -y nodejs npm

查看版本:

node -v
npm -v

⚠️ Debian 仓库中的 Node.js 通常较旧,不推荐用于现代前端或后端开发。


✅ 方法三:使用 NVM(推荐给开发者)

适合多版本切换、本地开发环境。

1️⃣ 安装 NVM

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

重新加载 shell:

source ~/.bashrc

2️⃣ 安装 Node.js(LTS 示例)

nvm install --lts

3️⃣ 设置默认版本

nvm use --lts
nvm alias default lts/*

4️⃣ 验证

node -v
npm -v

✅ Node.js 环境基本配置(推荐)

1️⃣ 配置 npm 国内镜像(可选)

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

2️⃣ 安装常用工具

npm install -g yarn pnpm

✅ 常见问题

❓ 是否需要安装 build-essential

如果你需要编译原生模块(如 bcryptsqlite3):

sudo apt install -y build-essential

❓ 如何卸载 Node.js?

  • apt 安装
sudo apt remove nodejs
  • nvm 安装
nvm uninstall <version>

✅ 推荐方案总结

场景 推荐方式
生产环境 / 新项目 ✅ NodeSource
本地开发 / 多版本 ✅ NVM
快速测试 apt

如果你愿意,可以告诉我:

  • Debian 版本(如 11 / 12)
  • 用途(前端 / 后端 / 服务器)
  • 是否需要 PM2、Docker、Nginx 配合

我可以给你一套更精确的配置方案

0