当前推荐使用 Node.js 22 LTS 版本,原生支持 ES Module、
fetchAPI、WebSocket 客户端、node:test测试框架等现代特性。
访问 Node.js 官网下载对应系统的安装包:
推荐使用 nvm 管理多个 Node.js 版本:
# 安装 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
# 安装最新 LTS 版本
nvm install --lts
# 安装指定版本
nvm install 22
# 切换版本
nvm use 22
# 查看已安装版本
nvm ls
# 查看可安装版本
nvm ls-remote# 全局安装 n
npm install -g n
# 安装最新版本
n latest
# 安装 LTS 版本
n lts
# 安装指定版本
n 22
# 切换版本
nfnm 基于 Rust 构建,启动速度比 nvm 快 40 倍以上,跨平台支持:
# macOS 安装
brew install fnm
# Linux 安装
curl -fsSL https://fnm.vercel.app/install | bash
# Windows 安装
winget install Schniz.fnm
# 安装 LTS 版本
fnm install --lts
# 安装指定版本
fnm install 22
# 使用指定版本
fnm use 22
# 设置默认版本
fnm default 22
# 配置 shell 自动切换(添加到 .zshrc / .bashrc)
eval "$(fnm env --use-on-cd)"# 查看 Node.js 版本
node -v
# 查看 npm 版本
npm -v
# 查看 Node.js 安装路径
which node
# 查看 npm 安装路径
which npm由于网络原因,建议配置国内镜像源:
# 查看当前镜像源
npm config get registry
# 设置淘宝镜像源
npm config set registry https://registry.npmmirror.com
# 设置官方镜像源
npm config set registry https://registry.npmjs.org
# 使用 nrm 管理镜像源
npm install -g nrm
nrm ls # 查看所有镜像源
nrm use taobao # 切换到淘宝镜像
nrm test # 测试镜像源速度npm 配置文件位置:
~/.npmrc项目根目录/.npmrc$PREFIX/etc/npmrc常用配置项:
# 查看所有配置
npm config list
# 设置配置项
npm config set <key> <value>
# 删除配置项
npm config delete <key>
# 常用配置
npm config set registry https://registry.npmmirror.com # 镜像源
npm config set prefix "~/.npm-global" # 全局安装路径
npm config set cache "~/.npm-cache" # 缓存路径将全局安装的包添加到 PATH:
# 编辑 ~/.bashrc 或 ~/.zshrc
export PATH=~/.npm-global/bin:$PATH
# 使配置生效
source ~/.bashrc
# 或
source ~/.zshrc在项目根目录创建 .vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/app.js"
},
{
"type": "node",
"request": "attach",
"name": "Attach to Process",
"port": 9229
}
]
}在 macOS/Linux 上避免使用 sudo:
# 创建全局安装目录
mkdir ~/.npm-global
# 配置 npm 使用新目录
npm config set prefix '~/.npm-global'
# 添加到 PATH
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc# 清理缓存
npm cache clean --force
# 验证缓存
npm cache verify# 删除 node_modules
rm -rf node_modules
# 删除 package-lock.json
rm package-lock.json
# 重新安装
npm install无需安装 nodemon,Node.js 22+ 原生支持文件监视:
# 监视文件变更并自动重启
node --watch app.js
# 监视指定路径
node --watch-path=./src app.js
# 配合 --env-file 使用
node --watch --env-file=.env app.jsNode.js 22.6+ 支持直接运行 TypeScript 文件(仅移除类型注解):
# Node.js 22.6 - 23.5
node --experimental-strip-types app.ts
# Node.js 23.6+ 默认启用
node app.ts
# 禁用类型剥离(如果需要)
node --no-experimental-strip-types app.jsNode.js 20.6+ 内置支持 .env 文件,无需 dotenv 库:
# 加载 .env 文件
node --env-file=.env app.js
# 加载不同环境的配置
node --env-file=.env.production app.js
node --env-file=.env.development app.jsNode.js 23+ 稳定的 --run 命令,替代 npm run:
# 运行 package.json 中的脚本
node --run build
node --run test
node --run devNode.js 22.13+ 权限模型已稳定,增强安全性:
# 启用权限模型
node --permission app.js
# 允许文件系统读取
node --allow-fs-read=./data app.js
# 允许网络访问
node --allow-net=api.example.com:443 app.js