Update Node automatically in different environments using NVM

📅January 12, 2023

🕒4 minute read

🏷

node

nvm

javascript

environment

Problem: You work on different JavaScript projects and each codebase uses a different version of Node.

Different versions of Node on distinct codebases doesn't sound like your ideal work week, but this is something we all run into sometime or another.

NVM already solves the issue with giving us the ability to manually change the version of node that we want to use (nvm use), and thats fantastic. But jumping around codebases on the daily can lead to some headaches when we encounter one of the famous variants of the npm ERR! gyp ERR! error and don't know why.

Steps to automatically update Node version

This can be leveraged by adding a script to your shell config. I use zsh so I add this to my ~/.zshrc:

# place this after nvm initialization!

autoload -U add-zsh-hook

load-nvmrc() {
  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" != "$(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

If you instead use bash or any other shell, you can check out this section on the nvm docs which write on this subject.

After this, all you have to do is add an .nvmrc file to your projects' root directory and your shell will automatically update node depending on what this file specifies.

Example of .nvmrc file:

v18.12.1