Skip to content

Node 版本管理器

¥Node Version Manager

简介

¥Intro

nvm 允许你通过命令行快速安装和使用不同版本的 Node.js。

¥nvm allows you to quickly install and use different versions of node via the command line.

示例:

¥Example:

sh
$ nvm use 16
Now using node v16.9.1 (npm v7.21.1)
$ node -v
v16.9.1
$ nvm use 14
Now using node v14.18.0 (npm v6.14.15)
$ node -v
v14.18.0
$ nvm install 12
Now using node v12.22.6 (npm v6.14.5)
$ node -v
v12.22.6

就这么简单!

¥Simple as that!

关于

¥About

nvm 是 node.js 的版本管理器,旨在按用户安装,并按 shell 调用。nvm 适用于任何符合 POSIX 标准的 shell(sh、dash、ksh、zsh、bash),尤其是在以下平台上:unix、macOS 和 Windows WSL

¥nvm is a version manager for node.js, designed to be installed per-user, and invoked per-shell. nvm works on any POSIX-compliant shell (sh, dash, ksh, zsh, bash), in particular on these platforms: unix, macOS, and windows WSL.

安装和更新

¥Installing and Updating

安装和更新脚本

¥Install & Update Script

要安装或更新 nvm,你应该运行 安装脚本。为此,你可以手动下载并运行脚本,也可以使用以下 cURL 或 Wget 命令:

¥To install or update nvm, you should run the install script. To do that, you may either download and run the script manually, or use the following cURL or Wget command:

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

运行上述任一命令都会下载并运行脚本。该脚本将 nvm 仓库克隆到 ~/.nvm,并尝试将以下代码片段中的源代码行添加到正确的配置文件(~/.bashrc~/.bash_profile~/.zshrc~/.profile)。如果你发现安装脚本更新了错误的配置文件,请将 $PROFILE 的环境变量设置为配置文件的路径,然后重新运行安装脚本。

¥Running either of the above commands downloads a script and runs it. The script clones the nvm repository to ~/.nvm, and attempts to add the source lines from the snippet below to the correct profile file (~/.bashrc, ~/.bash_profile, ~/.zshrc, or ~/.profile). If you find the install script is updating the wrong profile file, set the $PROFILE env var to the profile file’s path, and then rerun the installation script.

sh
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm

附加说明

¥Additional Notes

  • 如果存在环境变量 $XDG_CONFIG_HOME,它会将 nvm 文件放置在那里。

    ¥If the environment variable $XDG_CONFIG_HOME is present, it will place the nvm files there.

  • 你可以将 --no-use 添加到上述脚本的末尾,以推迟使用 nvm,直到你手动 use 它:

    ¥You can add --no-use to the end of the above script to postpone using nvm until you manually use it:

sh
export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" --no-use # This loads nvm, without auto-using the default version
  • 你可以使用 NVM_SOURCENVM_DIRPROFILENODE_VERSION 变量自定义安装源、目录、配置文件和版本。例如:curl ... | NVM_DIR="path/to/nvm"。确保 NVM_DIR 不包含尾部斜杠。

    ¥You can customize the install source, directory, profile, and version using the NVM_SOURCE, NVM_DIR, PROFILE, and NODE_VERSION variables. Eg: curl ... | NVM_DIR="path/to/nvm". Ensure that the NVM_DIR does not contain a trailing slash.

  • 安装程序可以使用 gitcurlwget 下载 nvm(以可用版本为准)。

    ¥The installer can use git, curl, or wget to download nvm, whichever is available.

  • 你可以通过在运行 install.sh 脚本之前设置 PROFILE=/dev/null,指示安装程序不要编辑你的 shell 配置(例如,如果你已经通过 zsh nvm 插件 获得了补全信息)。以下是执行此操作的单行命令示例:PROFILE=/dev/null bash -c 'curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash'

    ¥You can instruct the installer to not edit your shell config (for example if you already get completions via a zsh nvm plugin) by setting PROFILE=/dev/null before running the install.sh script. Here's an example one-line command to do that: PROFILE=/dev/null bash -c 'curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash'

在 Docker 中安装

¥Installing in Docker

当以非交互式 shell 形式调用 bash 时(例如在 Docker 容器中),不会获取任何常规配置文件。为了像平常一样使用 nvmnodenpm,你可以指定特殊的 BASH_ENV 变量,该变量在非交互方式调用时会引用 bash 源代码。

¥When invoking bash as a non-interactive shell, like in a Docker container, none of the regular profile files are sourced. In order to use nvm, node, and npm like normal, you can instead specify the special BASH_ENV variable, which bash sources when invoked non-interactively.

Dockerfile
# Use bash for the shell
SHELL ["/bin/bash", "-o", "pipefail", "-c"]

# Create a script file sourced by both interactive and non-interactive bash shells
ENV BASH_ENV /home/user/.bash_env
RUN touch "${BASH_ENV}"
RUN echo '. "${BASH_ENV}"' >> ~/.bashrc

# Download and install nvm
RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | PROFILE="${BASH_ENV}" bash
RUN echo node > .nvmrc
RUN nvm install
在 Docker 中安装 CICD 作业

¥Installing in Docker for CICD-Jobs

更健壮,适用于 CI/CD 作业。可以在交互式和非交互式容器中运行。参见 https://github.com/nvm-sh/nvm/issues/3531

¥More robust, works in CI/CD-Jobs. Can be run in interactive and non-interactive containers. See https://github.com/nvm-sh/nvm/issues/3531.

Dockerfile
FROM ubuntu:latest
ARG NODE_VERSION=20

# install curl
RUN apt update && apt install curl -y

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

# set env
ENV NVM_DIR=/root/.nvm

# install node
RUN bash -c "source $NVM_DIR/nvm.sh && nvm install $NODE_VERSION"

# set ENTRYPOINT for reloading nvm-environment
ENTRYPOINT ["bash", "-c", "source $NVM_DIR/nvm.sh && exec \"$@\"", "--"]

# set cmd to bash
CMD ["/bin/bash"]

此示例默认安装的是 nodejs 版本 20.x.y。你也可以使用 docker build args 轻松覆盖版本,例如:

¥This example defaults to installation of nodejs version 20.x.y. Optionally you can easily override the version with docker build args like:

docker build -t nvmimage --build-arg NODE_VERSION=19 .

创建镜像后,你可以以交互方式启动容器并运行命令,例如:

¥After creation of the image you can start container interactively and run commands, for example:

docker run --rm -it nvmimage

root@0a6b5a237c14:/# nvm -v
0.40.3

root@0a6b5a237c14:/# node -v
v19.9.0

root@0a6b5a237c14:/# npm -v
9.6.3

非交互示例:

¥Noninteractive example:

user@host:/tmp/test $ docker run --rm -it nvmimage node -v
v19.9.0
user@host:/tmp/test $ docker run --rm -it nvmimage npm -v
9.6.3

故障排除 Linux

¥Troubleshooting on Linux

在 Linux 上,运行安装脚本后,如果你在输入 command -v nvm 后出现 nvm: command not found 或终端没有返回任何反馈,请关闭当前终端,打开一个新终端,然后再次尝试验证。或者,你也可以在命令行中为不同的 shell 运行以下命令:

¥On Linux, after running the install script, if you get nvm: command not found or see no feedback from your terminal after you type command -v nvm, simply close your current terminal, open a new terminal, and try verifying again. Alternatively, you can run the following commands for the different shells on the command line:

bash:source ~/.bashrc

zsh:source ~/.zshrc

ksh:. ~/.profile

这些颜色应该会使用 nvm 命令。

¥These should pick up the nvm command.

macOS 故障排除

¥Troubleshooting on macOS

自 OS X 10.9 起,Xcode 命令行工具已预设 /usr/bin/git,这意味着我们无法正确检测 Git 是否已安装。你需要在运行安装脚本之前手动安装 Xcode 命令行工具,否则安装会失败。(参见 #1782

¥Since OS X 10.9, /usr/bin/git has been preset by Xcode command line tools, which means we can't properly detect if Git is installed or not. You need to manually install the Xcode command line tools before running the install script, otherwise, it'll fail. (see #1782)

如果运行安装脚本后出现 nvm: command not found 错误,则可能是以下原因之一:

¥If you get nvm: command not found after running the install script, one of the following might be the reason:

  • 自 macOS 10.15 起,默认 shell 为 zsh,nvm 会查找 .zshrc 进行更新,默认情况下未安装任何 .zshrc。使用 touch ~/.zshrc 创建其中一个,然后再次运行安装脚本。

    ¥Since macOS 10.15, the default shell is zsh and nvm will look for .zshrc to update, none is installed by default. Create one with touch ~/.zshrc and run the install script again.

  • 如果你使用 bash(之前的默认 Shell),你的系统可能没有设置命令的 .bash_profile.bashrc 文件。使用 touch ~/.bash_profiletouch ~/.bashrc 创建其中一个,然后再次运行安装脚本。然后,运行 . ~/.bash_profile. ~/.bashrc 来获取 nvm 命令。

    ¥If you use bash, the previous default shell, your system may not have .bash_profile or .bashrc files where the command is set up. Create one of them with touch ~/.bash_profile or touch ~/.bashrc and run the install script again. Then, run . ~/.bash_profile or . ~/.bashrc to pick up the nvm command.

  • 你之前使用过 bash,但你安装了 zsh。你需要手动将 以下几行 添加到 ~/.zshrc 并运行 . ~/.zshrc

    ¥You have previously used bash, but you have zsh installed. You need to manually add these lines to ~/.zshrc and run . ~/.zshrc.

  • 你可能需要重启终端实例或运行 . ~/.nvm/nvm.sh。重启终端/打开新标签页/窗口,或运行 source 命令将加载该命令和新配置。

    ¥You might need to restart your terminal instance or run . ~/.nvm/nvm.sh. Restarting your terminal/opening a new tab/window, or running the source command will load the command and the new configuration.

  • 如果上述方法无效,你可能需要重启终端实例。尝试在终端中打开新的选项卡/窗口,然后重试。

    ¥If the above didn't help, you might need to restart your terminal instance. Try opening a new tab/window in your terminal and retry.

如果上述方法仍无法解决问题,你可以尝试以下操作:

¥If the above doesn't fix the problem, you may try the following:

  • 如果你使用 bash,则可能是你的 .bash_profile(或 ~/.profile)没有正确获取 ~/.bashrc。你可以通过添加 source ~/<your_profile_file> 或按照以下步骤操作来解决这个问题。

    ¥If you use bash, it may be that your .bash_profile (or ~/.profile) does not source your ~/.bashrc properly. You could fix this by adding source ~/<your_profile_file> to it or following the next step below.

  • 尝试将 安装部分的代码片段(它会找到正确的 nvm 目录并加载 nvm)添加到你常用的配置文件(~/.bash_profile~/.zshrc~/.profile~/.bashrc)中。

    ¥Try adding the snippet from the install section, that finds the correct nvm directory and loads nvm, to your usual profile (~/.bash_profile, ~/.zshrc, ~/.profile, or ~/.bashrc).

  • 有关此问题的更多信息和可能的解决方法,请参阅 请参阅此处

    ¥For more information about this issue and possible workarounds, please refer here

注意:对于搭载 Apple Silicon 芯片的 Mac,Node 从 v16.0.0 开始提供 arm64 arch Darwin 软件包,并从 v14.17.0 开始在源代码编译时提供实验性的 arm64 支持。如果你在使用 nvm 安装 Node 时遇到问题,你可能需要更新到该版本或更高版本。

¥Note For Macs with the Apple Silicon chip, node started offering arm64 arch Darwin packages since v16.0.0 and experimental arm64 support when compiling from source since v14.17.0. If you are facing issues installing node using nvm, you may want to update to one of those versions or later.

Ansible

你可以使用任务:

¥You can use a task:

yaml
- name: Install nvm
  ansible.builtin.shell: >
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
  args:
    creates: "{{ ansible_env.HOME }}/.nvm/nvm.sh"

验证安装

¥Verify Installation

要验证 nvm 是否已安装后,请执行以下操作:

¥To verify that nvm has been installed, do:

sh
command -v nvm

如果安装成功,应该输出 nvm。请注意,which nvm 无法运行,因为 nvm 是一个源 shell 函数,而不是可执行二进制文件。

¥which should output nvm if the installation was successful. Please note that which nvm will not work, since nvm is a sourced shell function, not an executable binary.

注意:在 Linux 上,运行安装脚本后,如果你在输入 command -v nvm 后出现 nvm: command not found 或终端没有返回任何反馈,请关闭当前终端,打开一个新终端,然后再次尝试验证。

¥Note: On Linux, after running the install script, if you get nvm: command not found or see no feedback from your terminal after you type command -v nvm, simply close your current terminal, open a new terminal, and try verifying again.

重要说明

¥Important Notes

如果你运行的系统没有可用的预打包二进制文件,这意味着你将从其源代码安装 node 或 io.js,你需要确保你的系统具有 C++ 编译器。对于 OS X,Xcode 可以使用;对于基于 Debian/Ubuntu 的 GNU/Linux,build-essentiallibssl-dev 软件包可以使用。

¥If you're running a system without prepackaged binary available, which means you're going to install node or io.js from its source code, you need to make sure your system has a C++ compiler. For OS X, Xcode will work, for Debian/Ubuntu based GNU/Linux, the build-essential and libssl-dev packages work.

注意:nvm 在某些情况下也支持 Windows。它应该可以通过 WSL(适用于 Linux 的 Windows 子系统)工作,具体取决于 WSL 的版本。它也应该适用于 GitBash (MSYS) 或 Cygwin。此外,对于 Windows,存在一些替代方案,但我们既不支持也不开发这些方案:

¥Note: nvm also supports Windows in some cases. It should work through WSL (Windows Subsystem for Linux) depending on the version of WSL. It should also work with GitBash (MSYS) or Cygwin. Otherwise, for Windows, a few alternatives exist, which are neither supported nor developed by us:

注意:nvm 也不支持 Fish(参见 #303)。存在其他替代方案,但我们不支持或未开发这些替代方案:

¥Note: nvm does not support Fish either (see #303). Alternatives exist, which are neither supported nor developed by us:

  • bass 允许你在 Fish Shell 中使用为 Bash 编写的实用程序。

    ¥bass allows you to use utilities written for Bash in fish shell

  • fast-nvm-fish 仅适用于版本号(不支持别名),但不会显著降低 Shell 启动速度。

    ¥fast-nvm-fish only works with version numbers (not aliases) but doesn't significantly slow your shell startup

  • Oh My Fishplugin-nvm 插件,使 nvm 及其补全功能在 Fish Shell 中可用。

    ¥plugin-nvm plugin for Oh My Fish, which makes nvm and its completions available in fish shell

  • nvm.fish - 你一定会喜欢的 Node.js 版本管理器,专为 Fish 打造

    ¥nvm.fish - The Node.js version manager you'll adore, crafted just for Fish

  • fish-nvm - 用于 fish 的 nvm 封装器,延迟获取 nvm,直到实际使用时再进行。

    ¥fish-nvm - Wrapper around nvm for fish, delays sourcing nvm until it's actually used.

注意:我们在使用 FreeBSD 时仍然存在一些问题,因为 FreeBSD 没有官方预构建的二进制文件,从源代码构建可能需要 patches;查看问题单:

¥Note: We still have some problems with FreeBSD, because there is no official pre-built binary for FreeBSD, and building from source may need patches; see the issue ticket:

注意:在 OS X 上,如果你没有安装 Xcode 并且不想下载大约 4.3GB 的文件,则可以安装 Command Line Tools。你可以查看这篇博文,了解如何操作:

¥Note: On OS X, if you do not have Xcode installed and you do not wish to download the ~4.3GB file, you can install the Command Line Tools. You can check out this blog post on how to just that:

注意:在 OS X 上,如果你已经安装了 "system" node 并希望全局安装模块,请记住:

¥Note: On OS X, if you have/had a "system" node installed and want to install modules globally, keep in mind that:

  • 使用 nvm 时,无需使用 sudo 来全局安装带有 npm -g 的模块,因此不要执行 sudo npm install -g grunt,而是执行 npm install -g grunt

    ¥When using nvm you do not need sudo to globally install a module with npm -g, so instead of doing sudo npm install -g grunt, do instead npm install -g grunt

  • 如果你有 ~/.npmrc 文件,请确保其中不包含任何 prefix 设置(与 nvm 不兼容)。

    ¥If you have an ~/.npmrc file, make sure it does not contain any prefix settings (which is not compatible with nvm)

  • 你可以(但不应该?)保留之前的 "system" node 安装,但 nvm 仅适用于你的用户账户(用于安装 nvm 的用户账户)。这可能会导致版本不匹配,因为其他用户可能使用 /usr/local/lib/node_modules/*,而你的用户账户可能使用 ~/.nvm/versions/node/vX.X.X/lib/node_modules/*

    ¥You can (but should not?) keep your previous "system" node install, but nvm will only be available to your user account (the one used to install nvm). This might cause version mismatches, as other users will be using /usr/local/lib/node_modules/* VS your user account using ~/.nvm/versions/node/vX.X.X/lib/node_modules/*

不支持 Homebrew 安装。如果你在使用 Homebrew 安装的 nvm 时遇到问题,请先将其 brew uninstall 化,然后按照以下说明进行安装,然后再提交问题。

¥Homebrew installation is not supported. If you have issues with homebrew-installed nvm, please brew uninstall it, and install it using the instructions below, before filing an issue.

注意:如果你使用的是 zsh,你可以轻松地将 nvm 安装为 zsh 插件。安装 zsh-nvm 并运行 nvm upgrade 进行升级(你可以设置 NVM_AUTO_USE=true 可使其自动检测并使用 .nvmrc 文件)。

¥Note: If you're using zsh you can easily install nvm as a zsh plugin. Install zsh-nvm and run nvm upgrade to upgrade (you can set NVM_AUTO_USE=true to have it automatically detect and use .nvmrc files).

注意:v1.7 之前的 Git 版本可能会遇到通过 https 协议从 GitHub 克隆 nvm 源代码的问题,v1.6 之前的 Git 行为也有所不同,而 v1.17.10 之前的 Git 可能会遇到不克隆标签,因此最低要求的 git 版本为 v1.7.10。如果你对我们在此处提到的问题感兴趣,请参阅 GitHub 的 HTTPS 克隆错误 文章。

¥Note: Git versions before v1.7 may face a problem of cloning nvm source from GitHub via https protocol, and there is also different behavior of git before v1.6, and git prior to v1.17.10 can not clone tags, so the minimum required git version is v1.7.10. If you are interested in the problem we mentioned here, please refer to GitHub's HTTPS cloning errors article.

Git 安装

¥Git Install

如果你已安装 git(需要 git v1.7.10+):

¥If you have git installed (requires git v1.7.10+):

  1. 将此 repo 克隆到你的用户配置文件根目录中

    ¥clone this repo in the root of your user profile

    • 在任何地方使用 cd ~/ 都比使用 git clone https://github.com/nvm-sh/nvm.git .nvm 好。

      ¥cd ~/ from anywhere then git clone https://github.com/nvm-sh/nvm.git .nvm

  2. 使用 cd ~/.nvm 并使用 git checkout v0.40.3 获取最新版本。

    ¥cd ~/.nvm and check out the latest version with git checkout v0.40.3

  3. 通过从你的 shell 获取 nvm 来激活它:. ./nvm.sh

    ¥activate nvm by sourcing it from your shell: . ./nvm.sh

现在,将以下几行添加到你的 ~/.bashrc~/.profile~/.zshrc 文件中,以便在登录时自动执行:(你可能需要添加多个上述文件)

¥Now add these lines to your ~/.bashrc, ~/.profile, or ~/.zshrc file to have it automatically sourced upon login: (you may have to add to more than one of the above files)

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

手动安装

¥Manual Install

对于完全手动安装,请执行以下行,首先将 nvm 存储库克隆到 $HOME/.nvm,然后加载 nvm

¥For a fully manual install, execute the following lines to first clone the nvm repository into $HOME/.nvm, and then load nvm:

sh
export NVM_DIR="$HOME/.nvm" && (
  git clone https://github.com/nvm-sh/nvm.git "$NVM_DIR"
  cd "$NVM_DIR"
  git checkout `git describe --abbrev=0 --tags --match "v[0-9]*" $(git rev-list --tags --max-count=1)`
) && \. "$NVM_DIR/nvm.sh"

现在,将以下几行添加到你的 ~/.bashrc~/.profile~/.zshrc 文件中,以便在登录时自动执行:(你可能需要添加多个上述文件)

¥Now add these lines to your ~/.bashrc, ~/.profile, or ~/.zshrc file to have it automatically sourced upon login: (you may have to add to more than one of the above files)

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

手动升级

¥Manual Upgrade

使用 git 手动升级(需要 git v1.7.10+):

¥For manual upgrade with git (requires git v1.7.10+):

  1. 更改为 $NVM_DIR

    ¥change to the $NVM_DIR

  2. 下载最新更改

    ¥pull down the latest changes

  3. 查看最新版本

    ¥check out the latest version

  4. 激活新版本

    ¥activate the new version

sh
(
  cd "$NVM_DIR"
  git fetch --tags origin
  git checkout `git describe --abbrev=0 --tags --match "v[0-9]*" $(git rev-list --tags --max-count=1)`
) && \. "$NVM_DIR/nvm.sh"

用法

¥Usage

要下载、编译和安装最新版本的 Node,请执行以下操作:

¥To download, compile, and install the latest release of node, do this:

sh
nvm install node # "node" is an alias for the latest version

要安装特定版本的 Node:

¥To install a specific version of node:

sh
nvm install 14.7.0 # or 16.3.0, 12.22.1, etc

设置别名:

¥To set an alias:

sh
nvm alias my_alias v14.4.0

确保你的别名不包含任何空格或斜杠。

¥Make sure that your alias does not contain any spaces or slashes.

第一个安装的版本将成为默认版本。新的 shell 将从默认的 Node 版本(例如 nvm alias default)开始。

¥The first version installed becomes the default. New shells will start with the default version of node (e.g., nvm alias default).

你可以使用 ls-remote 列出可用版本:

¥You can list available versions using ls-remote:

sh
nvm ls-remote

然后在任何新的 shell 中,只需使用已安装的版本即可:

¥And then in any new shell just use the installed version:

sh
nvm use node

或者你可以直接运行它:

¥Or you can just run it:

sh
nvm run node --version

或者,你可以在子 shell 中使用所需的 node 版本运行任意命令:

¥Or, you can run any arbitrary command in a subshell with the desired version of node:

sh
nvm exec 4.2 node --version

你还可以获取可执行文件的安装路径:

¥You can also get the path to the executable to where it was installed:

sh
nvm which 12.22

除了像 "14.7"、"16.3" 或 "12.22.1" 这样的版本指针之外,你还可以使用以下特殊的默认别名(例如 nvm installnvm usenvm runnvm execnvm which 等):

¥In place of a version pointer like "14.7" or "16.3" or "12.22.1", you can use the following special default aliases with nvm install, nvm use, nvm run, nvm exec, nvm which, etc:

  • node:这将安装 node 的最新版本

    ¥node: this installs the latest version of node

  • iojs:这将安装 io.js 的最新版本

    ¥iojs: this installs the latest version of io.js

  • stable:此别名已弃用,仅适用于 node v0.12 及更早版本。目前,这是 node 的别名。

    ¥stable: this alias is deprecated, and only truly applies to node v0.12 and earlier. Currently, this is an alias for node.

  • unstable:此别名指向 node v0.11 - 最后一个 "unstable" node 版本,自 1.0 之后,所有 node 版本都是稳定的。(在 SemVer 中,版本传达的是崩溃情况,而不是稳定性)。

    ¥unstable: this alias points to node v0.11 - the last "unstable" node release, since post-1.0, all node versions are stable. (in SemVer, versions communicate breakage, not stability).

长期支持

¥Long-term Support

Node 的长期支持 (LTS) 版本号为 schedule。你可以在别名和 .nvmrc 文件中引用 LTS 版本,例如,使用 lts/* 表示最新的 LTS,使用 lts/argon 表示 "argon" 系列的 LTS 版本。此外,以下命令支持 LTS 参数:

¥Node has a schedule for long-term support (LTS) You can reference LTS versions in aliases and .nvmrc files with the notation lts/* for the latest LTS, and lts/argon for LTS releases from the "argon" line, for example. In addition, the following commands support LTS arguments:

  • nvm install --lts / nvm install --lts=argon / nvm install 'lts/*' / nvm install lts/argon

  • nvm uninstall --lts / nvm uninstall --lts=argon / nvm uninstall 'lts/*' / nvm uninstall lts/argon

  • nvm use --lts / nvm use --lts=argon / nvm use 'lts/*' / nvm use lts/argon

  • nvm exec --lts / nvm exec --lts=argon / nvm exec 'lts/*' / nvm exec lts/argon

  • nvm run --lts / nvm run --lts=argon / nvm run 'lts/*' / nvm run lts/argon

  • nvm ls-remote --lts / nvm ls-remote --lts=argon nvm ls-remote 'lts/*' / nvm ls-remote lts/argon

  • nvm version-remote --lts / nvm version-remote --lts=argon / nvm version-remote 'lts/*' / nvm version-remote lts/argon

每当你的本地 nvm 副本连接到 https://nodejs.cn 时,它都会为所有可用的 LTS 版本重新创建相应的本地别名。这些别名(存储在 $NVM_DIR/alias/lts 下)由 nvm 管理,你不应修改、删除或创建这些文件。 - 你的更改可能会被撤消,并且修改这些文件可能会导致可能不受支持的 bug。

¥Any time your local copy of nvm connects to https://nodejs.cn, it will re-create the appropriate local aliases for all available LTS lines. These aliases (stored under $NVM_DIR/alias/lts), are managed by nvm, and you should not modify, remove, or create these files - expect your changes to be undone, and expect meddling with these files to cause bugs that will likely not be supported.

要获取最新的 LTS 版本的 Node 并迁移你现有的已安装软件包,请使用

¥To get the latest LTS version of node and migrate your existing installed packages, use

sh
nvm install --reinstall-packages-from=current 'lts/*'

安装过程中迁移全局包

¥Migrating Global Packages While Installing

如果你想安装新版本的 Node.js 并从旧版本迁移 npm 包:

¥If you want to install a new version of Node.js and migrate npm packages from a previous version:

sh
nvm install --reinstall-packages-from=node node

这将首先使用 "nvm 版本 node" 来识别你正在从中迁移软件包的当前版本。然后,它会从远程服务器解析要安装的新版本并进行安装。最后,它运行 "nvm reinstall-packages" 将 npm 包从旧版本的 Node 重新安装到新版本。

¥This will first use "nvm version node" to identify the current version you're migrating packages from. Then it resolves the new version to install from the remote server and installs it. Lastly, it runs "nvm reinstall-packages" to reinstall the npm packages from your prior version of Node to the new one.

你还可以像这样从特定版本的 Node 安装和迁移 npm 包:

¥You can also install and migrate npm packages from specific versions of Node like this:

sh
nvm install --reinstall-packages-from=5 6
nvm install --reinstall-packages-from=iojs v4.2

请注意,重新安装软件包不会更新 npm 版本 - 这是为了确保 npm 不会意外升级到新 Node 版本的错误版本。

¥Note that reinstalling packages explicitly does not update the npm version — this is to ensure that npm isn't accidentally upgraded to a broken version for the new node version.

要同时更新 npm,请添加 --latest-npm 标志,如下所示:

¥To update npm at the same time add the --latest-npm flag, like this:

sh
nvm install --reinstall-packages-from=default --latest-npm 'lts/*'

或者,你可以随时运行以下命令获取当前 node 版本支持的最新 npm 版本:

¥or, you can at any time run the following command to get the latest supported npm version on the current node version:

sh
nvm install-latest-npm

如果你已经遇到了与 "npm 不支持 Node.js" 相关的错误,则需要 (1) 恢复到之前的 Node 版本(nvm lsnvm use <your latest _working_ version from the ls>),(2) 删除新创建的 Node 版本 (nvm uninstall <your _broken_ version of node from the ls>),然后 (3) 使用 --latest-npm 标志重新运行 nvm install

¥If you've already gotten an error to the effect of "npm does not support Node.js", you'll need to (1) revert to a previous node version (nvm ls & nvm use <your latest _working_ version from the ls>), (2) delete the newly created node version (nvm uninstall <your _broken_ version of node from the ls>), then (3) rerun your nvm install with the --latest-npm flag.

安装时从文件中获取默认全局包

¥Default Global Packages From File While Installing

如果你有每次安装新版本时都希望安装的默认软件包列表,我们也支持这样做 - 只需将软件包名称(每行一个)添加到 $NVM_DIR/default-packages 文件中即可。你可以在命令行中添加 npm 可以接受的任何包参数。

¥If you have a list of default packages you want installed every time you install a new version, we support that too -- just add the package names, one per line, to the file $NVM_DIR/default-packages. You can add anything npm would accept as a package argument on the command line.

sh
# $NVM_DIR/default-packages

rimraf
object-inspect@1.0.2
stevemao/left-pad

io.js

如果你想安装 io.js

¥If you want to install io.js:

sh
nvm install iojs

如果你想安装新版本的 io.js 并从旧版本迁移 npm 包:

¥If you want to install a new version of io.js and migrate npm packages from a previous version:

sh
nvm install --reinstall-packages-from=iojs iojs

在 Node 中迁移 npm 软件包时提到的相同指南也适用于 io.js。

¥The same guidelines mentioned for migrating npm packages in node are applicable to io.js.

Node 的系统版本

¥System Version of Node

如果你想使用系统安装的 node 版本,可以使用特殊的默认别名 "system":

¥If you want to use the system-installed version of node, you can use the special default alias "system":

sh
nvm use system
nvm run system --version

列发布本

¥Listing Versions

如果你想查看已安装的版本:

¥If you want to see what versions are installed:

sh
nvm ls

如果你想查看有哪些版本可供安装:

¥If you want to see what versions are available to install:

sh
nvm ls-remote

设置自定义颜色

¥Setting Custom Colors

你可以设置五种颜色来显示版本和别名信息。这些颜色将替换默认颜色。初始颜色:g b y r e

¥You can set five colors that will be used to display version and alias information. These colors replace the default colors. Initial colors are: g b y r e

颜色代码:

¥Color codes:

r/R = red / bold red

g/G = green / bold green

b/B = blue / bold blue

c/C = cyan / bold cyan

m/M = magenta / bold magenta

y/Y = yellow / bold yellow

k/K = black / bold black

e/W = light grey / white
sh
nvm set-colors rgBcm

保留自定义颜色

¥Persisting custom colors

如果你希望在终止 Shell 后保留自定义颜色,请在 Shell 配置文件中导出 NVM_COLORS 变量。例如,如果你想使用青色、洋红色、绿色、粗红色和粗黄色,请添加以下行:

¥If you want the custom colors to persist after terminating the shell, export the NVM_COLORS variable in your shell profile. For example, if you want to use cyan, magenta, green, bold red and bold yellow, add the following line:

sh
export NVM_COLORS='cmgRY'

隐藏彩色输出

¥Suppressing colorized output

nvm help (or -h or --help)nvm lsnvm ls-remotenvm alias 通常会生成彩色输出。你可以使用 --no-colors 选项(或通过设置环境变量 TERM=dumb)禁用颜色:

¥nvm help (or -h or --help), nvm ls, nvm ls-remote and nvm alias usually produce colorized output. You can disable colors with the --no-colors option (or by setting the environment variable TERM=dumb):

sh
nvm ls --no-colors
nvm help --no-colors
TERM=dumb nvm ls

恢复 PATH

¥Restoring PATH

要恢复 PATH,你可以停用它:

¥To restore your PATH, you can deactivate it:

sh
nvm deactivate

设置默认 Node 版本

¥Set default node version

要设置在任何新 shell 中使用的默认 Node 版本,请使用别名 'default':

¥To set a default Node version to be used in any new shell, use the alias 'default':

sh
nvm alias default node # this refers to the latest installed version of node
nvm alias default 18 # this refers to the latest installed v18.x version of node
nvm alias default 18.12  # this refers to the latest installed v18.12.x version of node

使用 Node 二进制文件的镜像

¥Use a mirror of node binaries

要使用 Node 二进制文件的镜像,请设置 $NVM_NODEJS_ORG_MIRROR

¥To use a mirror of the node binaries, set $NVM_NODEJS_ORG_MIRROR:

sh
export NVM_NODEJS_ORG_MIRROR=https://nodejs.cn/dist
nvm install node

NVM_NODEJS_ORG_MIRROR=https://nodejs.cn/dist nvm install 4.2

要使用 io.js 二进制文件的镜像,请设置 $NVM_IOJS_ORG_MIRROR

¥To use a mirror of the io.js binaries, set $NVM_IOJS_ORG_MIRROR:

sh
export NVM_IOJS_ORG_MIRROR=https://iojs.org/dist
nvm install iojs-v1.0.3

NVM_IOJS_ORG_MIRROR=https://iojs.org/dist nvm install iojs-v1.0.3

默认情况下,nvm use 不会创建 "current" 符号链接。将 $NVM_SYMLINK_CURRENT 设置为 "true" 即可启用此行为,这有时对 IDE 很有用。请注意,在启用此环境变量的情况下,在多个 shell 选项卡中使用 nvm 可能会导致竞争条件。

¥nvm use will not, by default, create a "current" symlink. Set $NVM_SYMLINK_CURRENT to "true" to enable this behavior, which is sometimes useful for IDEs. Note that using nvm in multiple shell tabs with this environment variable enabled can cause race conditions.

将授权标头传递给镜像

¥Pass Authorization header to mirror

要将授权标头传递到镜像 URL,请设置 $NVM_AUTH_HEADER

¥To pass an Authorization header through to the mirror url, set $NVM_AUTH_HEADER

sh
NVM_AUTH_HEADER="Bearer secret-token" nvm install node

.nvmrc

你可以在项目根目录(或任何父目录)中创建一个包含 Node 版本号(或 nvm 识别的任何其他字符串;详情请参阅 nvm --help)的 .nvmrc 文件。之后,如果命令行中未提供版本,nvm usenvm installnvm execnvm runnvm which 将使用 .nvmrc 文件中指定的版本。

¥You can create a .nvmrc file containing a node version number (or any other string that nvm understands; see nvm --help for details) in the project root directory (or any parent directory). Afterwards, nvm use, nvm install, nvm exec, nvm run, and nvm which will use the version specified in the .nvmrc file if no version is supplied on the command line.

例如,要将 nvm 默认设置为当前目录的最新 5.9 版本、最新 LTS 版本或最新 Node 版本:

¥For example, to make nvm default to the latest 5.9 release, the latest LTS version, or the latest node version for the current directory:

sh
$ echo "5.9" > .nvmrc

$ echo "lts/*" > .nvmrc # to default to the latest LTS version

$ echo "node" > .nvmrc # to default to the latest version

[注意:这些示例假设 echo 的 shell 版本符合 POSIX 标准。如果你使用 Windows cmd 开发环境,例如,.nvmrc 文件用于配置远程 Linux 部署,请记住," 将被复制,从而导致文件无效。删除它们。]

¥[NB these examples assume a POSIX-compliant shell version of echo. If you use a Windows cmd development environment, eg the .nvmrc file is used to configure a remote Linux deployment, then keep in mind the "s will be copied leading to an invalid file. Remove them.]

然后,当你运行 nvm 时,请使用:

¥Then when you run nvm use:

sh
$ nvm use
Found '/path/to/project/.nvmrc' with version <5.9>
Now using node v5.9.1 (npm v3.7.3)

运行 nvm install 也会切换到正确的版本,但如果尚未安装正确的 node 版本,它将自动安装。

¥Running nvm install will also switch over to the correct version, but if the correct node version isn't already installed, it will install it for you.

sh
$ nvm install
Found '/path/to/project/.nvmrc' with version <5.9>
Downloading and installing node v5.9.1...
Downloading https://nodejs.cn/dist/v5.9.1/node-v5.9.1-linux-x64.tar.xz...
#################################################################################### 100.0%
Computing checksum with sha256sum
Checksums matched!
Now using node v5.9.1 (npm v3.7.3)

nvm use 等。al。将从当前目录向上遍历目录结构,查找 .nvmrc 文件。换句话说,运行 nvm use 等。al。在包含 .nvmrc 的目录的任何子目录中,都会导致使用 .nvmrc

¥nvm use et. al. will traverse directory structure upwards from the current directory looking for the .nvmrc file. In other words, running nvm use et. al. in any subdirectory of a directory with an .nvmrc will result in that .nvmrc being utilized.

.nvmrc 文件的内容必须恰好包含一个 <version>(如 nvm --help 所述),后跟一个换行符。.nvmrc 文件也可能包含注释。注释分隔符为 #,它及其后的任何文本、空行以及前后空格在解析时都将被忽略。

¥The contents of a .nvmrc file must contain precisely one <version> (as described by nvm --help) followed by a newline. .nvmrc files may also have comments. The comment delimiter is #, and it and any text after it, as well as blank lines, and leading and trailing white space, will be ignored when parsing.

使用 = 的键/值对也是允许和忽略的,但保留以供将来使用,并且可能会导致将来的验证错误。

¥Key/value pairs using = are also allowed and ignored, but are reserved for future use, and may cause validation errors in the future.

运行 npx nvmrc 以验证 .nvmrc 文件。如果该工具的结果与 nvm 不一致,则说明其中一个存在错误。 - 请提交问题。

¥Run npx nvmrc to validate an .nvmrc file. If that tool’s results do not agree with nvm, one or the other has a bug - please file an issue.

更深层次的 Shell 集成

¥Deeper Shell Integration

你可以使用 nvshim 来填充 nodenpmnpx 的 bin 文件,以自动使用当前目录中的 nvm 配置。nvm 维护者不支持 nvshim。请 nvshim 团队报告问题

¥You can use nvshim to shim the node, npm, and npx bins to automatically use the nvm config in the current directory. nvshim is not supported by the nvm maintainers. Please report issues to the nvshim team.

如果你更喜欢更轻量级的解决方案,以下配方是由 nvm 用户贡献的。nvm 维护者不支持它们。但是,我们接受更多示例的拉取请求。

¥If you prefer a lighter-weight solution, the recipes below have been contributed by nvm users. They are not supported by the nvm maintainers. We are, however, accepting pull requests for more examples.

在包含 .nvmrc 文件的目录中自动调用 nvm use

¥Calling nvm use automatically in a directory with a .nvmrc file

在你的配置文件(~/.bash_profile~/.zshrc~/.profile~/.bashrc)中,每当你进入新目录时,请将以下内容添加到 nvm use 中:

¥In your profile (~/.bash_profile, ~/.zshrc, ~/.profile, or ~/.bashrc), add the following to nvm use whenever you enter a new directory:

bash

将以下内容添加到你的 $HOME/.bashrc 末尾:

¥Put the following at the end of your $HOME/.bashrc:

bash
cdnvm() {
    command cd "$@" || return $?
    nvm_path="$(nvm_find_up .nvmrc | command tr -d '\n')"

    # If there are no .nvmrc file, use the default nvm version
    if [[ ! $nvm_path = *[^[:space:]]* ]]; then

        declare default_version
        default_version="$(nvm version default)"

        # If there is no default version, set it to `node`
        # This will use the latest version on your machine
        if [ $default_version = 'N/A' ]; then
            nvm alias default node
            default_version=$(nvm version default)
        fi

        # If the current version is not the default version, set it to use the default version
        if [ "$(nvm current)" != "${default_version}" ]; then
            nvm use default
        fi
    elif [[ -s "${nvm_path}/.nvmrc" && -r "${nvm_path}/.nvmrc" ]]; then
        declare nvm_version
        nvm_version=$(<"${nvm_path}"/.nvmrc)

        declare locally_resolved_nvm_version
        # `nvm ls` will check all locally-available versions
        # If there are multiple matching versions, take the latest one
        # Remove the `->` and `*` characters and spaces
        # `locally_resolved_nvm_version` will be `N/A` if no local versions are found
        locally_resolved_nvm_version=$(nvm ls --no-colors "${nvm_version}" | command tail -1 | command tr -d '\->*' | command tr -d '[:space:]')

        # If it is not already installed, install it
        # `nvm install` will implicitly use the newly-installed version
        if [ "${locally_resolved_nvm_version}" = 'N/A' ]; then
            nvm install "${nvm_version}";
        elif [ "$(nvm current)" != "${locally_resolved_nvm_version}" ]; then
            nvm use "${nvm_version}";
        fi
    fi
}

alias cd='cdnvm'
cdnvm "$PWD" || exit

此别名将从当前目录中搜索 'up' 以检测 .nvmrc 文件。如果找到,它将切换到该版本;如果不是,它将使用默认版本。

¥This alias would search 'up' from your current directory in order to detect a .nvmrc file. If it finds it, it will switch to that version; if not, it will use the default version.

zsh

此 shell 函数将安装(如果需要)并在找到 .nvmrcnvm use 指定的 Node 版本,否则 nvm use default

¥This shell function will install (if needed) and nvm use the specified Node version when an .nvmrc is found, and nvm use default otherwise.

将此内容添加到你的 $HOME/.zshrc 中,以便在你进入包含 .nvmrc 文件的目录时自动调用 nvm use,该文件包含一个字符串,告知 nvm use 对应的 node:

¥Put this into your $HOME/.zshrc to call nvm use automatically whenever you enter a directory that contains an .nvmrc file with a string telling nvm which node to use:

zsh
# place this after nvm initialization!
autoload -U add-zsh-hook

load-nvmrc() {
  local nvmrc_path
  nvmrc_path="$(nvm_find_nvmrc)"

  if [ -n "$nvmrc_path" ]; then
    local nvmrc_node_version
    nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")")

    if [ "$nvmrc_node_version" = "N/A" ]; then
      nvm install
    elif [ "$nvmrc_node_version" != "$(nvm version)" ]; then
      nvm use
    fi
  elif [ -n "$(PWD=$OLDPWD nvm_find_nvmrc)" ] && [ "$(nvm version)" != "$(nvm version default)" ]; then
    echo "Reverting to nvm default version"
    nvm use default
  fi
}

add-zsh-hook chpwd load-nvmrc
load-nvmrc

保存文件后,运行 source ~/.zshrc 以重新加载包含最新更改的配置。

¥After saving the file, run source ~/.zshrc to reload the configuration with the latest changes made.

fish

这需要你安装 bass

¥This requires that you have bass installed.

fish
# ~/.config/fish/functions/nvm.fish
function nvm
  bass source ~/.nvm/nvm.sh --no-use ';' nvm $argv
end

# ~/.config/fish/functions/nvm_find_nvmrc.fish
function nvm_find_nvmrc
  bass source ~/.nvm/nvm.sh --no-use ';' nvm_find_nvmrc
end

# ~/.config/fish/functions/load_nvm.fish
function load_nvm --on-variable="PWD"
  set -l default_node_version (nvm version default)
  set -l node_version (nvm version)
  set -l nvmrc_path (nvm_find_nvmrc)
  if test -n "$nvmrc_path"
    set -l nvmrc_node_version (nvm version (cat $nvmrc_path))
    if test "$nvmrc_node_version" = "N/A"
      nvm install (cat $nvmrc_path)
    else if test "$nvmrc_node_version" != "$node_version"
      nvm use $nvmrc_node_version
    end
  else if test "$node_version" != "$default_node_version"
    echo "Reverting to default Node version"
    nvm use default
  end
end

# ~/.config/fish/config.fish
# You must call it on initialization or listening to directory switching won't work
load_nvm > /dev/stderr

运行测试

¥Running Tests

测试使用 Urchin 编写。像这样安装 Urchin(及其他依赖):

¥Tests are written in Urchin. Install Urchin (and other dependencies) like so:

npm install

慢速测试和快速测试都有。慢速测试会执行诸如安装 Node 之类的操作,并检查是否使用了正确的版本。快速测试会模拟此情况,以测试别名和卸载等操作。从 nvm git 存储库的根目录,像这样运行快速测试:

¥There are slow tests and fast tests. The slow tests do things like install node and check that the right versions are used. The fast tests fake this to test things like aliases and uninstalling. From the root of the nvm git repository, run the fast tests like this:

npm run test/fast

像这样运行慢速测试:

¥Run the slow tests like this:

npm run test/slow

像这样运行所有测试:

¥Run all of the tests like this:

npm test

注意:避免在测试运行时运行 nvm。

¥Nota bene: Avoid running nvm while the tests are running.

环境变量

¥Environment variables

nvm 公开以下环境变量:

¥nvm exposes the following environment variables:

  • NVM_DIR - nvm 的安装目录。

    ¥NVM_DIR - nvm's installation directory.

  • NVM_BIN - 其中安装了当前 node 版本对应的 node、npm 和全局包。

    ¥NVM_BIN - where node, npm, and global packages for the active version of node are installed.

  • NVM_INC - node 的包含文件目录(用于构建 node 的 C/C++ 插件)。

    ¥NVM_INC - node's include file directory (useful for building C/C++ addons for node).

  • NVM_CD_FLAGS - 用于保持与 zsh 的兼容性。

    ¥NVM_CD_FLAGS - used to maintain compatibility with zsh.

  • NVM_RC_VERSION - 如果使用,则从 .nvmrc 文件中获取版本。

    ¥NVM_RC_VERSION - version from .nvmrc file if being used.

此外,nvm 在更改版本时会修改 PATH,如果存在,还会修改 MANPATHNODE_PATH

¥Additionally, nvm modifies PATH, and, if present, MANPATH and NODE_PATH when changing versions.

Bash 补全

¥Bash Completion

要激活,你需要 source bash_completion

¥To activate, you need to source bash_completion:

sh
[[ -r $NVM_DIR/bash_completion ]] && \. $NVM_DIR/bash_completion

请将上述源行放在你的配置文件中 nvm 源行(.bashrc.bash_profile)的正下方。

¥Put the above sourcing line just below the sourcing line for nvm in your profile (.bashrc, .bash_profile).

用法

¥Usage

nvm:

$ nvm Tab

sh
alias               deactivate          install             list-remote         reinstall-packages  uninstall           version
cache               exec                install-latest-npm  ls                  run                 unload              version-remote
current             help                list                ls-remote           unalias             use                 which

nvm 别名:

¥nvm alias:

$ nvm alias Tab

sh
default      iojs         lts/*        lts/argon    lts/boron    lts/carbon   lts/dubnium  lts/erbium   node         stable       unstable

$ nvm alias my_alias Tab

sh
v10.22.0       v12.18.3      v14.8.0

nvm 使用:

¥nvm use:

$ nvm use Tab

my_alias        default        v10.22.0       v12.18.3      v14.8.0

nvm uninstall:

$ nvm uninstall Tab

my_alias        default        v10.22.0       v12.18.3      v14.8.0

兼容性问题

¥Compatibility Issues

如果你设置了一些非默认设置,nvm 将会遇到一些问题。(参见 #606)以下情况已知会导致问题:

¥nvm will encounter some issues if you have some non-default settings set. (see #606) The following are known to cause issues:

~/.npmrc 内部:

¥Inside ~/.npmrc:

sh
prefix='some/path'

环境变量:

¥Environment Variables:

sh
$NPM_CONFIG_PREFIX
$PREFIX

Shell 设置:

¥Shell settings:

sh
set -e

在 Alpine Linux 上安装 nvm

¥Installing nvm on Alpine Linux

为了提供最佳性能(以及其他优化),nvm 会在你运行 nvm install X 时下载并安装 Node(和 npm)的预编译二进制文件。Node 项目编译、测试并托管/提供这些为主流/传统 Linux 发行版(例如 Debian、Ubuntu、CentOS、RedHat 等)构建的预编译二进制文件。

¥In order to provide the best performance (and other optimizations), nvm will download and install pre-compiled binaries for Node (and npm) when you run nvm install X. The Node project compiles, tests and hosts/provides these pre-compiled binaries which are built for mainstream/traditional Linux distributions (such as Debian, Ubuntu, CentOS, RedHat et al).

与主流/传统 Linux 发行版不同,Alpine Linux 基于 BusyBox,这是一款非常紧凑(约 5MB)的 Linux 发行版。BusyBox(以及 Alpine Linux)使用的 C/C++ 堆栈与大多数主流/传统 Linux 发行版不同。 - musl。这使得为主流/传统 Linux 构建的二进制程序与 Alpine Linux 不兼容,因此我们不能简单地在 Alpine Linux 上运行 nvm install X 并期望下载的二进制程序能够正确运行。 - 如果你尝试这样做,你可能会看到 "...不存在" 错误。

¥Alpine Linux, unlike mainstream/traditional Linux distributions, is based on BusyBox, a very compact (~5MB) Linux distribution. BusyBox (and thus Alpine Linux) uses a different C/C++ stack to most mainstream/traditional Linux distributions - musl. This makes binary programs built for such mainstream/traditional incompatible with Alpine Linux, thus we cannot simply nvm install X on Alpine Linux and expect the downloaded binary to run correctly - you'll likely see "...does not exist" errors if you try that.

nvm install 有一个 -s 标志,它请求 nvm 下载 Node 源代码并在本地进行编译。

¥There is a -s flag for nvm install which requests nvm download Node source and compile it locally.

如果你仍然想或需要在 Alpine Linux 上安装 nvm,那么你应该能够通过在 Alpine Linux shell 中运行以下命令来实现,具体取决于你使用的版本:

¥If installing nvm on Alpine Linux is still what you want or need to do, you should be able to achieve this by running the following from you Alpine Linux shell, depending on which version you are using:

Alpine Linux 3.13+

sh
apk add -U curl bash ca-certificates openssl ncurses coreutils python3 make gcc g++ libgcc linux-headers grep util-linux binutils findutils
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash

Alpine Linux 3.5 - 3.12

sh
apk add -U curl bash ca-certificates openssl ncurses coreutils python2 make gcc g++ libgcc linux-headers grep util-linux binutils findutils
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash

注意:Alpine 3.5 只能安装最高 v6.9.5 版本的 NodeJS,Alpine 3.6 只能安装最高 v6.10.3 版本的 NodeJS,Alpine 3.7 可以安装最高 v8.9.3 版本的 NodeJS,Alpine 3.8 可以安装最高 v8.14.0 版本的 NodeJS,Alpine 3.9 可以安装最高 v10.19.0 版本的 NodeJS,Alpine 3.10 可以安装最高 v10.24.1 版本的 NodeJS,Alpine 3.11 可以安装最高 v12.22.6 版本的 NodeJS,Alpine 3.12 可以安装最高 v12.22.12 版本的 NodeJS,Alpine 3.13 和 3.14 可以安装最高 v10.24.1 版本的 NodeJS v14.20.0、Alpine 3.15 和 3.16 安装版本最高可达 v16.16.0(这些都是主分支上的版本)。Alpine 3.5 - 3.12 需要 python2 软件包来构建 NodeJS,因为它们是旧版本。Alpine 3.13+ 需要 python3 才能成功构建较新的 NodeJS 版本,但如果你需要构建 Alpine 3.5 支持的 Node 版本,则可以将 python2 与 Alpine 3.13+ 结合使用。 - 3.15 版本中,你只需在软件包安装脚本中指定需要安装的 NodeJS 版本即可。

¥Note: Alpine 3.5 can only install NodeJS versions up to v6.9.5, Alpine 3.6 can only install versions up to v6.10.3, Alpine 3.7 installs versions up to v8.9.3, Alpine 3.8 installs versions up to v8.14.0, Alpine 3.9 installs versions up to v10.19.0, Alpine 3.10 installs versions up to v10.24.1, Alpine 3.11 installs versions up to v12.22.6, Alpine 3.12 installs versions up to v12.22.12, Alpine 3.13 & 3.14 install versions up to v14.20.0, Alpine 3.15 & 3.16 install versions up to v16.16.0 (These are all versions on the main branch). Alpine 3.5 - 3.12 required the package python2 to build NodeJS, as they are older versions to build. Alpine 3.13+ requires python3 to successfully build newer NodeJS versions, but you can use python2 with Alpine 3.13+ if you need to build versions of node supported in Alpine 3.5 - 3.15, you just need to specify what version of NodeJS you need to install in the package install script.

Node 项目有一些愿望,但目前没有具体计划(由于构建、测试和支持的开销)提供与 Alpine 兼容的二进制文件。

¥The Node project has some desire but no concrete plans (due to the overheads of building, testing and support) to offer Alpine-compatible binaries.

作为一种潜在的替代方案,@mhart(一位 Node 贡献者)有一些 预装 Node 和可选 npm 的 Alpine Linux Docker 镜像

¥As a potential alternative, @mhart (a Node contributor) has some Docker images for Alpine Linux with Node and optionally, npm, pre-installed.

卸载/移除

¥Uninstalling / Removal

手动卸载

¥Manual Uninstall

要手动删除 nvm,请执行以下操作:

¥To remove nvm manually, execute the following:

首先,使用 nvm unload 从终端会话中删除 nvm 命令并删除安装目录:

¥First, use nvm unload to remove the nvm command from your terminal session and delete the installation directory:

sh
$ nvm_dir="${NVM_DIR:-~/.nvm}"
$ nvm unload
$ rm -rf "$nvm_dir"

编辑 ~/.bashrc(或其他 shell 资源配置)并删除以下行:

¥Edit ~/.bashrc (or other shell resource config) and remove the lines below:

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

Docker 开发环境

¥Docker For Development Environment

为了简化开发和测试工作,我们提供了一个用于开发的 Dockerfile,它基于 Ubuntu 18.04 基础镜像,并配备了 nvm 开发所需的基本工具。要构建环境的 Docker 镜像,请在 nvm 仓库的根目录下运行 docker 命令:

¥To make the development and testing work easier, we have a Dockerfile for development usage, which is based on Ubuntu 18.04 base image, prepared with essential and useful tools for nvm development, to build the docker image of the environment, run the docker command at the root of nvm repository:

sh
$ docker build -t nvm-dev .

这会将你当前的 nvm 存储库与我们预定义的开发环境打包到名为 nvm-dev 的 Docker 镜像中。成功构建后,通过 docker images 验证你的镜像:

¥This will package your current nvm repository with our pre-defined development environment into a docker image named nvm-dev, once it's built with success, validate your image via docker images:

sh
$ docker images

REPOSITORY         TAG                 IMAGE ID            CREATED             SIZE
nvm-dev            latest              9ca4c57a97d8        7 days ago          650 MB

如果你没有收到错误消息,现在你可以轻松参与:

¥If you got no error message, now you can easily involve in:

sh
$ docker run -h nvm-dev -it nvm-dev

nvm@nvm-dev:~/.nvm$

请注意,构建镜像大约需要 8 分钟,镜像大小约为 650MB,因此不适合用于生产环境。

¥Please note that it'll take about 8 minutes to build the image and the image size would be about 650MB, so it's not suitable for production usage.

有关 docker 的更多信息和文档,请参阅其官方网站:

¥For more information and documentation about docker, please refer to its official website:

问题

¥Problems

  • 如果你尝试安装某个 Node 版本但安装失败,请务必运行 nvm cache clear 命令以删除缓存的 Node 下载文件,否则你可能会收到如下错误:

    ¥If you try to install a node version and the installation fails, be sure to run nvm cache clear to delete cached node downloads, or you might get an error like the following:

    curl:(33)HTTP 服务器似乎不支持字节范围。无法恢复。

    ¥curl: (33) HTTP server doesn't seem to support byte ranges. Cannot resume.

  • 我的 sudo node 在哪里?查看 #43

    ¥Where's my sudo node? Check out #43

  • 在 Node v0.8.6 版本之后,nvm 会尝试从二进制软件包安装。但在某些系统中,由于共享库不兼容,官方二进制软件包无法运行。在这种情况下,请使用 -s 选项强制从源安装:

    ¥After the v0.8.6 release of node, nvm tries to install from binary packages. But in some systems, the official binary packages don't work due to incompatibility of shared libs. In such cases, use -s option to force install from source:

sh
nvm install -s 0.8.6
  • 如果设置 default 别名无法在新 shell 中确定 node 版本(例如,nvm current 生成 system),请确保在 shell 配置文件中,在 nvm.sh 源代码行之前设置系统的 node PATH(参见 #658)。

    ¥If setting the default alias does not establish the node version in new shells (i.e. nvm current yields system), ensure that the system's node PATH is set before the nvm.sh source line in your shell profile (see #658)

macOS 故障排除

¥macOS Troubleshooting

在 vim shell 中未找到 nvm node 版本

¥nvm node version not found in vim shell

如果你将 Node 版本设置为系统 Node 版本 nvm use 6.2.1 以外的版本,然后打开 Vim 并运行 :!node -v,如果你看到的是系统版本 v0.12.7,则应该看到 v6.2.1。你需要运行:

¥If you set node version to a version other than your system node version nvm use 6.2.1 and open vim and run :!node -v you should see v6.2.1 if you see your system version v0.12.7. You need to run:

shell
sudo chmod ugo-x /usr/libexec/path_helper

有关此问题的更多信息,请参阅 dotphiles/dotzsh

¥More on this issue in dotphiles/dotzsh.

nvm 与 npm config "prefix" 选项不兼容

¥nvm is not compatible with the npm config "prefix" option

此问题的一些解决方案可在 此处 中找到。

¥Some solutions for this issue can be found here

还有一个极端情况会导致此问题,那就是 $HOME 路径与用户主目录的实际名称不匹配。

¥There is one more edge case causing this issue, and that's a mismatch between the $HOME path and the user's home directory's actual name.

你必须确保 $HOME 中的用户目录名和运行 ls /Users/ 后看到的用户目录名大小写一致 (查看此问题)。

¥You have to make sure that the user directory name in $HOME and the user directory name you'd see from running ls /Users/ are capitalized the same way (See this issue).

要更改用户目录和/或账户名,请按照 此处 的说明操作。

¥To change the user directory and/or account name follow the instructions here

Homebrew 使 zsh 目录不安全

¥Homebrew makes zsh directories unsecure

shell
zsh compinit: insecure directories, run compaudit for list.
Ignore insecure directories and continue [y] or abort compinit [n]? y

Homebrew 会导致目录不安全,例如 /usr/local/share/zsh/site-functions/usr/local/share/zsh。这不是 nvm 的问题 - 这是自制软件的问题。有关此问题的一些解决方案,请参阅 此处

¥Homebrew causes insecure directories like /usr/local/share/zsh/site-functions and /usr/local/share/zsh. This is not an nvm problem - it is a homebrew problem. Refer here for some solutions related to the issue.

搭载 Apple Silicon 芯片的 Mac

¥Macs with Apple Silicon chips

在 node.js v15.3 中添加了对 Apple Silicon 芯片架构的实验性支持,并在 v16.0 中添加了全面支持。因此,如果你尝试像往常一样安装旧版本的 Node,你可能会在安装 Node 时遇到编译错误,或者在运行代码时遇到内存不足错误。

¥Experimental support for the Apple Silicon chip architecture was added in node.js v15.3 and full support was added in v16.0. Because of this, if you try to install older versions of node as usual, you will probably experience either compilation errors when installing node or out-of-memory errors while running your code.

因此,如果你想在 Apple Silicon Mac 上运行 v16.0 之前的版本,最好编译针对 x86_64 Intel 架构的 Node.js 程序,以便 Rosetta 2 能够将 x86_64 处理器指令转换为基于 ARM 的 Apple Silicon 指令。你需要执行以下操作:

¥So, if you want to run a version prior to v16.0 on an Apple Silicon Mac, it may be best to compile node targeting the x86_64 Intel architecture so that Rosetta 2 can translate the x86_64 processor instructions to ARM-based Apple Silicon instructions. Here's what you will need to do:

  • 如果你尚未安装 Rosetta,请先安装。

    ¥Install Rosetta, if you haven't already done so

    sh
    $ softwareupdate --install-rosetta

    你可能会想,"我的 Apple Silicon Mac 如何知道使用 Rosetta 来运行为 Intel 芯片编译的 Node 版本?"。如果可执行文件仅包含 Intel 指令,macOS 将自动使用 Rosetta 翻译指令。

    ¥You might wonder, "how will my Apple Silicon Mac know to use Rosetta for a version of node compiled for an Intel chip?". If an executable contains only Intel instructions, macOS will automatically use Rosetta to translate the instructions.

  • 打开一个使用 Rosetta 运行的 shell

    ¥Open a shell that's running using Rosetta

    sh
    $ arch -x86_64 zsh

    注意:同样的操作也可以通过在 Finder 中找到终端或 iTerm 应用,右键单击,选择 "获取信息",然后选中标有 "使用 Rosetta 打开" 的框来实现。

    ¥Note: This same thing can also be accomplished by finding the Terminal or iTerm App in Finder, right clicking, selecting "Get Info", and then checking the box labeled "Open using Rosetta".

    注意:此终端会话现在正在 zsh 中运行。如果 zsh 不是你通常使用的 shell,nvm 可能不会像通过点文件对常用 shell 那样自动 source。如果是这种情况,请确保执行 nvm 的 source 命令。

    ¥Note: This terminal session is now running in zsh. If zsh is not the shell you typically use, nvm may not be source'd automatically like it probably is for your usual shell through your dotfiles. If that's the case, make sure to source nvm.

    sh
    $ source "${NVM_DIR}/nvm.sh"
  • 安装你感兴趣的任何旧版本的 Node。我们以 12.22.1 为例。这将获取 Node 源代码并进行编译,这将需要几分钟时间。

    ¥Install whatever older version of node you are interested in. Let's use 12.22.1 as an example. This will fetch the node source code and compile it, which will take several minutes.

    sh
    $ nvm install v12.22.1 --shared-zlib

    注意:你可能很好奇为什么包含 --shared-zlib。Apple 系统 clang 编译器的最新版本存在一个错误。如果你的系统上安装了其中一个损坏的版本,即使你没有添加 --shared-zlib 标志,上述步骤仍然可能成功。但是,稍后当你尝试使用旧版本的 node.js npm install 某些内容时,你将看到 incorrect data check 错误。如果你想避免处理此问题可能带来的麻烦,请包含该标志。更多详情,请参阅 这个问题此评论

    ¥Note: You're probably curious why --shared-zlib is included. There's a bug in recent versions of Apple's system clang compiler. If one of these broken versions is installed on your system, the above step will likely still succeed even if you didn't include the --shared-zlib flag. However, later, when you attempt to npm install something using your old version of node.js, you will see incorrect data check errors. If you want to avoid the possible hassle of dealing with this, include that flag. For more details, see this issue and this comment

  • 退出并返回到你的原生 shell。

    ¥Exit back to your native shell.

    sh
    $ exit
    $ arch
    arm64

    注意:如果你在第二步中选择了标有 "使用 Rosetta 打开" 的框而不是运行 CLI 命令,你将在此处看到 i386。除非你有其他理由选中该框,否则你现在可以取消选中它。

    ¥Note: If you selected the box labeled "Open using Rosetta" rather than running the CLI command in the second step, you will see i386 here. Unless you have another reason to have that box selected, you can deselect it now.

  • 请检查架构是否正确。x64x86_64 的缩写,这正是你想要看到的。

    ¥Check to make sure the architecture is correct. x64 is the abbreviation for x86_64, which is what you want to see.

    sh
    $ node -p process.arch
    x64

现在你应该可以照常使用 node 了。

¥Now you should be able to use node as usual.

WSL 故障排除

¥WSL Troubleshooting

如果你在 WSL-2 上遇到此错误:

¥If you've encountered this error on WSL-2:

sh
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                Dload  Upload  Total   Spent    Left  Speed
0     0    0     0    0     0      0      0 --:--:--  0:00:09 --:--:--     0curl: (6) Could not resolve host: raw.githubusercontent.com

这可能是由于你的防病毒软件、VPN 或其他原因造成的。

¥It may be due to your antivirus, VPN, or other reasons.

可以使用 ping 8.8.8.8 而不能使用 ping google.com 的情况

¥Where you can ping 8.8.8.8 while you can't ping google.com

只需在根目录中运行以下命令即可轻松解决此问题:

¥This could simply be solved by running this in your root directory:

sh
sudo rm /etc/resolv.conf
sudo bash -c 'echo "nameserver 8.8.8.8" > /etc/resolv.conf'
sudo bash -c 'echo "[network]" > /etc/wsl.conf'
sudo bash -c 'echo "generateResolvConf = false" >> /etc/wsl.conf'
sudo chattr +i /etc/resolv.conf

这将删除运行 WSL 时自动生成的 resolv.conf 文件,创建一个新文件并添加 nameserver 8.8.8.8 文件,然后创建一个 wsl.conf 文件并添加 [network]generateResolveConf = false 文件以防止该文件自动生成。

¥This deletes your resolv.conf file that is automatically generated when you run WSL, creates a new file and puts nameserver 8.8.8.8, then creates a wsl.conf file and adds [network] and generateResolveConf = false to prevent auto-generation of that file.

你可以通过运行以下命令检查文件内容:

¥You can check the contents of the file by running:

sh
cat /etc/resolv.conf

维护者

¥Maintainers

目前,唯一维护者是 @ljharb。 - 我们非常欢迎更多维护人员加入,并希望随着时间的推移不断有新成员加入团队。随着项目的发展,治理 将重新评估。

¥Currently, the sole maintainer is @ljharb - more maintainers are quite welcome, and we hope to add folks to the team over time. Governance will be re-evaluated as the project evolves.

项目支持

¥Project Support

目前仅支持最新版本(v0.40.3)。

¥Only the latest version (v0.40.3 at this time) is supported.

企业支持

¥Enterprise Support

如果你无法更新到 nvm 的最新版本,我们的 partners 为所有不受支持的版本提供了商业安全修复程序:

¥If you are unable to update to the latest version of nvm, our partners provide commercial security fixes for all unsupported versions:

许可证

¥License

参见 LICENSE.md

¥See LICENSE.md.

¥Copyright notice

版权所有 OpenJS 基金会nvm 贡献者。保留所有权利。OpenJS 基金会 已注册商标并使用其商标。有关 OpenJS 基金会 的商标列表,请参阅我们的 商标政策商标列表OpenJS 基金会商标列表 上未注明的商标和徽标均为其各自所有者的商标™或注册®商标。使用它们并不意味着与它们有任何关联或获得它们的认可。OpenJS 基金会 | 使用条款 | 隐私政策 | 章程 | 行为准则 | 商标政策 | 商标列表 | Cookie 政策

¥Copyright OpenJS Foundation and nvm contributors. All rights reserved. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. The OpenJS Foundation | Terms of Use | Privacy Policy | Bylaws | Code of Conduct | Trademark Policy | Trademark List | Cookie Policy