强曰为道
与天地相似,故不违。知周乎万物,而道济天下,故不过。旁行而不流,乐天知命,故不忧.
文档目录

Node.js 开发指南 / 第 2 章 · 安装与环境配置

第 2 章 · 安装与环境配置

2.1 版本管理工具对比

在正式安装 Node.js 之前,强烈建议使用版本管理工具,而非直接安装官方安装包。原因如下:

安装方式优点缺点
官方安装包简单直接难以切换版本,需要 sudo 权限
nvm(推荐)多版本共存、无需 sudo仅 macOS/Linux
fnm快速、跨平台生态较小
volta自动切换版本配置较复杂

2.2 安装 nvm

macOS / Linux

# 使用官方脚本安装
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash

# 或使用 wget
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash

安装完成后,重新打开终端或执行:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

验证安装

nvm --version
# 输出示例:0.40.1

Windows 用户

Windows 用户请使用 nvm-windows

# 使用 Chocolatey
choco install nvm

# 或使用 Scoop
scoop install nvm

也可使用 fnm(Fast Node Manager),原生跨平台:

# macOS / Linux
curl -fsSL https://fnm.vercel.app/install | bash

# Windows (PowerShell)
winget install Schniz.fnm

2.3 使用 nvm 管理 Node.js 版本

常用命令速查

命令说明
nvm ls-remote列出所有可安装版本
nvm install 22安装 Node.js 22.x 最新版
nvm install --lts安装最新 LTS 版本
nvm install 20.11.0安装指定版本
nvm use 22切换到 Node.js 22
nvm use --lts切换到最新 LTS
nvm ls列出已安装版本
nvm alias default 22设置默认版本
nvm uninstall 18卸载指定版本
nvm current显示当前使用的版本
nvm run 20 app.js使用指定版本运行脚本

安装和切换版本

# 安装最新 LTS 版本
nvm install --lts

# 安装特定版本
nvm install 22.12.0

# 安装多个版本
nvm install 20
nvm install 22

# 查看已安装版本
nvm ls
# ->     v20.18.1
#         v22.12.0
# default -> 22 (-> v22.12.0)
# node -> stable (-> v22.12.0)

# 切换版本
nvm use 20
# Now using node v20.18.1

nvm use 22
# Now using node v22.12.0

# 设置默认版本
nvm alias default 22

项目级版本管理

在项目根目录创建 .nvmrc 文件:

# 项目根目录
echo "22" > .nvmrc

# 进入项目目录时自动切换
cd my-project
nvm use
# Found '/home/user/my-project/.nvmrc' with version <22>
# Now using node v22.12.0

使用 engines 字段

package.json 中声明支持的 Node.js 版本:

{
  "name": "my-project",
  "engines": {
    "node": ">=20.0.0",
    "npm": ">=9.0.0"
  }
}

配合 npm config set engine-strict true 可在安装时强制检查版本。

2.4 配置 npm

npm 配置文件

# 查看当前配置
npm config list

# 设置淘宝镜像(国内加速)
npm config set registry https://registry.npmmirror.com

# 设置默认作者信息
npm config set init-author-name "Your Name"
npm config set init-author-email "your@email.com"
npm config set init-license "MIT"

# 查看所有配置
npm config list -l

npm 配置速查表

配置项说明推荐值
registry包注册表地址https://registry.npmmirror.com
save-exact精确版本号保存true
engine-strict强制检查 enginestrue
fund显示资助信息false
audit安全审计true

使用 .npmrc 文件

在项目根目录创建 .npmrc

registry=https://registry.npmmirror.com
save-exact=true
engine-strict=true
fund=false

了解 npx

npx 是 npm 附带的包执行工具:

# 运行本地安装的 CLI 工具
npx eslint src/

# 运行未安装的包(临时下载)
npx create-react-app my-app

# 指定版本运行
npx typescript@5.3 tsc --version

# 运行 GitHub 仓库
npx github:user/repo

2.5 IDE 配置

VS Code(推荐)

必装扩展

扩展名说明
ESLintJavaScript/TypeScript 代码检查
Prettier代码格式化
JavaScript (ES6) code snippetsES6+ 代码片段
Node.js Extension PackNode.js 开发扩展包
Thunder ClientREST API 测试工具(替代 Postman)
GitLensGit 增强工具
Error Lens行内显示错误和警告

VS Code 设置

在项目根目录创建 .vscode/settings.json

{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  },
  "javascript.updateImportsOnFileMove.enabled": "always",
  "javascript.suggest.autoImports": true,
  "typescript.suggest.autoImports": true,
  "files.eol": "\n",
  "files.trimTrailingWhitespace": true,
  "files.insertFinalNewline": true,
  "editor.tabSize": 2,
  "editor.rulers": [100],
  "search.exclude": {
    "node_modules": true,
    "package-lock.json": true
  }
}

调试配置

创建 .vscode/launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "启动程序",
      "program": "${workspaceFolder}/src/index.js",
      "skipFiles": ["<node_internals>/**"],
      "env": {
        "NODE_ENV": "development"
      }
    },
    {
      "type": "node",
      "request": "launch",
      "name": "运行当前文件",
      "program": "${file}",
      "skipFiles": ["<node_internals>/**"]
    },
    {
      "type": "node",
      "request": "attach",
      "name": "附加到进程",
      "port": 9229,
      "skipFiles": ["<node_internals>/**"]
    }
  ]
}

使用调试器启动:

# 使用 --inspect 标志启动
node --inspect src/index.js

# 使用 --inspect-brk 在第一行暂停
node --inspect-brk src/index.js

# 远程调试
node --inspect=0.0.0.0:9229 src/index.js

其他编辑器

编辑器Node.js 支持说明
WebStorm开箱即用功能最全,但收费
Neovim需配置 LSP使用 nvim-lspconfig + tsserver
Sublime Text需安装插件LSP-typescript

2.6 验证环境

创建验证脚本

// check-env.js
console.log('=== Node.js 环境检查 ===\n');

// Node.js 版本
console.log(`Node.js 版本: ${process.version}`);
console.log(`V8 版本: ${process.versions.v8}`);
console.log(`npm 版本: 请运行 npm -v 查看`);
console.log(`平台: ${process.platform}`);
console.log(`架构: ${process.arch}`);
console.log(`内存限制: ${Math.round(process.memoryUsage().heapTotal / 1024 / 1024)}MB`);

// 检查关键模块
const modules = ['fs', 'http', 'path', 'crypto', 'stream', 'events'];
console.log('\n=== 核心模块检查 ===');
modules.forEach(mod => {
  try {
    require(mod);
    console.log(`✅ ${mod} — 可用`);
  } catch {
    console.log(`❌ ${mod} — 不可用`);
  }
});

// 检查 ES Modules 支持
console.log('\n=== ES Modules 检查 ===');
console.log('ESM 支持: ✅(使用 .mjs 或 package.json type: "module")');

// 系统信息
console.log('\n=== 系统信息 ===');
console.log(`CPU 核心数: ${require('os').cpus().length}`);
console.log(`总内存: ${Math.round(require('os').totalmem() / 1024 / 1024 / 1024)}GB`);
console.log(`可用内存: ${Math.round(require('os').freemem() / 1024 / 1024 / 1024)}GB`);
console.log(`主目录: ${require('os').homedir()}`);
node check-env.js

预期输出:

=== Node.js 环境检查 ===

Node.js 版本: v22.12.0
V8 版本: 12.4.254.21-node.22
平台: linux
架构: x64
内存限制: 8MB

=== 核心模块检查 ===
✅ fs — 可用
✅ http — 可用
✅ path — 可用
✅ crypto — 可用
✅ stream — 可用
✅ events — 可用

注意事项

⚠️ 不要使用 root 权限安装全局包:使用 nvm 时,全局包安装在用户目录下,无需 sudo。

⚠️ 选择 LTS 版本:生产环境应使用 LTS(长期支持)版本,而非 Current 版本。偶数版本号(如 20、22)为 LTS,奇数版本号(如 21、23)为 Current。

⚠️ 国内镜像加速:npm 官方源在国内访问较慢,建议设置淘宝镜像或使用 cnpm

⚠️ 锁定依赖版本:始终将 package-lock.json 提交到 Git,确保团队成员使用相同依赖版本。

业务场景

  1. 团队开发:使用 .nvmrc.npmrc 确保所有开发者环境一致
  2. CI/CD 流水线:在 CI 中使用与本地相同的 Node.js 版本
  3. 多项目维护:不同项目可能需要不同 Node.js 版本,nvm 可轻松切换
  4. 新项目初始化:使用 npm init 配合预设配置快速创建项目

扩展阅读


上一章第 1 章 · Node.js 入门与概述 下一章第 3 章 · Hello World — 学习 REPL、脚本运行和模块系统初探。