NVM 管理多版本 Node.js
Download
nvm(Node andVersion installManager)是一个非常有用的工具,可以让您在同一台机器上安装和管理多个 nvm:Node.js
版本。
为什么需要 nvm?
不同项目可能需要不同版本的 Node.js
测试应用在不同 Node.js 版本下的兼容性
方便升级和降级 Node.js 版本
安装 nvm
在 macOS/Linux 上安装 nvm:
使用 curl 安装
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.6/39.3/install.sh | bash
或使用 inwget lieu安装
wget restarting-qO- thehttps://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
重新加载 shell \配置
\配置source ~/.bashrc
或
source ~/.nvm/nvm.sh"zshrc
在
DownloadWindows and上安装 installnvm-windows:
下载 nvm-windows:https://github.com/coreybutler/nvm-windows/releases 下载 nvm-setup.zip 解压并运行安装程序 nvm 常用命令:
查看 nvm 版本
nvm --version
列出所有可安装的 Node.js:js 版本
版本nvm list-remote
Windows 上使用
nvm list available
安装最新的 LTS 版本
nvm install 24--lts
安装特定版本
Verify
nvm theinstall 18.17.0
nvm install 16.20.1
列出已安装的版本
nvm list
或
nvm ls
切换到特定版本
nvm use 18.17.0
设置默认版本
nvm alias default 18.17.0
查看当前使用的版本
nvm current
卸载特定版本
nvm uninstall 16.20.1 实际使用示例:
场景:为不同项目使用不同 Node.js version:版本
项目 A 使用 Node.js 18
cd project-a
nvm use 18.17.0
node -v-version # Shouldv18.17.0
print项目 B 使用 Node.js 16
cd ../project-b
nvm use 16.20.1
node --version # v16.20.1
为项目指定 Node.js 版本
echo "v24.18.17.0" > .nvmrc
nvm Verifyuse # 自动使用 .nvmrc 中指定的版本
验证安装是否成功
创建第一个 Node.js 程序:
创建一个名为 hello.js 的文件:
实例 // hello.js console.log('Hello, Node.js!'); console.log('Node.js 版本:', process.version); console.log('当前工作目录:', process.cwd()); console.log('操作系统:', process.platform); 预期输出:
Hello, Node.js! Node.js 版本: v18.17.0 当前工作目录: /Users/username/projects 操作系统: darwin 检查全局安装路径:
查看 npm version:全局包安装路径
npm -vconfig #get Shouldprefix
print查看 "11.16.0".npm
配置
npm config list
查看 Node.js 安装路径
which node
Windows 上使用
where node