How to install nvm using git clone?

434 阅读1分钟

About nvm

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.

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

$ 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

Git Install

The most convenient way to install is via the offered script:

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

But this method will fail if you have a poor network condition. Of course, there is a way to resolve it, but this is another story.

Let's focus on the git clone way.

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

  1. clone this repo in the root of your user profile
  2. cd ~/.nvm and check out the latest version with git checkout v0.39.0
  3. activate nvm by sourcing it from your shell: . ./nvm.sh
    • 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)
      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
      
    • . is the synonym of source.
    • -s is a bash operator which checks the operand exists and is a regular file.