FE / js / node

About NVM

nvm (Node Version Manager) allows you to have different versions of node installed on your machine.

So, let say you inherited various projects; some on node 10, some on node 12 and some on node 14. nvm is there to cover you up.

Install

To install nvm you’ll have to run an installation script and then load nvm through your shell.

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


# load nvm within the shell
# in this case assumed zsh 
vim ~/.zshrc

# paste within ~/.zshrc
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

Config

To use nvm automatically all the time a .nvmrc file get detected.

vim ~/.zshrc

# paste within ~/.zshrc after the previous export

autoload -U add-zsh-hook

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

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

    if [ "$nvmrc_node_version" = "N/A" ]; then
      nvm install
    elif [ "$nvmrc_node_version" != "$node_version" ]; then
      nvm use
    fi
  elif [ "$node_version" != "$(nvm version default)" ]; then
    echo "Reverting to nvm default version"
    nvm use default
  fi
}

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

Usage

You can choose the node version to load with nvm directly in command line or specify the node version with a .nvmrc.

# load node version specified in .nvmrc
nvm use 

# install node version specified in .nvmrc
nvm install 

# load specific node version (before to use you need to install it)
nvm use 12.22.0

# install specific node version
nvm install 12.22.0

# list local installed node version
nvm ls

# list remote available node version
nvm ls-remote

# list remote available node version, filtering specific version
nvm ls-remote | grep 12.22

# set global default
nvm alias default 12.22.0

Tips

Having multiple node versions at the time may be handy to have a hint about the version you’re currently in. For that purpose, I do use and recommend spaceship-prompt.

In case your .zshrc is getting too messy have a look at ZSH script loader. If you use it nvm is configured out of the box.