Node.js NVM
在同一台机器上装多个 Node 版本并随时切换。
Key PointsNVM 通过改写 PATH 指向不同版本的目录来切换 Node,项目里放 `.nvmrc` 就能自动对齐。
常用命令
Bash
nvm ls-remote --lts # 看有哪些 LTS 版本
nvm install 20 # 装 20.x 最新
nvm install --lts # 装当前 LTS
nvm ls # 看本地已装
nvm use 20 # 切到 20
nvm alias default 22 # 设默认版本
nvm current # 当前版本
nvm uninstall 18 # 卸载Output
$ nvm ls
v18.20.4
-> v20.18.1
v22.22.2
default -> 22 (-> v22.22.2)项目里锁定版本
Bash
echo "22" > .nvmrc
nvm use # 自动读取 .nvmrcOutput
Found '.nvmrc' with version <22>
Now using node v22.22.2 (64-bit)With a shell hook, cd into the directory switches automatically:
Bash
# ~/.bashrc 末尾
cdnvm() {
cd "$@" || return
if [ -f .nvmrc ]; then nvm use --silent; fi
}
alias cd='cdnvm'nvm / n / fnm 怎么选
| Tool | Platform | Note |
|---|---|---|
| nvm | macOS / Linux | 最主流,shell 函数实现 |
| nvm-windows | Windows | 独立程序,和 nvm 命令基本一致 |
| fnm | 全平台 | Rust 写的,启动快 |
| n | macOS / Linux | 直接换全局软链,简单粗暴 |
Globally installed packages (
npm i -g typescript) do not follow you across versions. Each Node version has its own global directory — reinstall after switching.常用命令
Bash
nvm ls-remote --lts # 看有哪些 LTS 版本
nvm install 20 # 装 20.x 最新
nvm install --lts # 装当前 LTS
nvm ls # 看本地已装
nvm use 20 # 切到 20
nvm alias default 22 # 设默认版本
nvm current # 当前版本
nvm uninstall 18 # 卸载Output
$ nvm ls
v18.20.4
-> v20.18.1
v22.22.2
default -> 22 (-> v22.22.2)项目里锁定版本
Bash
echo "22" > .nvmrc
nvm use # 自动读取 .nvmrcOutput
Found '.nvmrc' with version <22>
Now using node v22.22.2 (64-bit)配合 shell 钩子,cd 进目录就自动切换:
Bash
# ~/.bashrc 末尾
cdnvm() {
cd "$@" || return
if [ -f .nvmrc ]; then nvm use --silent; fi
}
alias cd='cdnvm'nvm / n / fnm 怎么选
| 工具 | 平台 | 说明 |
|---|---|---|
| nvm | macOS / Linux | 最主流,shell 函数实现 |
| nvm-windows | Windows | 独立程序,和 nvm 命令基本一致 |
| fnm | 全平台 | Rust 写的,启动快 |
| n | macOS / Linux | 直接换全局软链,简单粗暴 |
切版本后全局安装的包(如
npm i -g typescript)不会跟着走。每个 Node 版本有独立的全局目录,切过去要重装。