NVM: How to automatically switch version when changing directories

Updated . Posted . Visible to the public. Repeats.

The Node Version Manager allows installing multiple NodeJS versions and switching between them.
By default, it does not automatically switch versions when entering a directory that holds a .nvmrc file.

The project's readme document Show archive.org snapshot offers a bash function which calls nvm use after each cd. In fact, it replaces cd in your bash.

I did not want to do that, but instead use the $PROMPT_COMMAND feature. So here is my take on it.
Note that it is much shorter, it probably does a few less smart things, but has been working great for me for a long while.
Also note that it compares .nvmrc file paths instead of comparing nvm current, so cding around subdirectories of your project should work without any noticable performance impact.

Bash

Put the following at the end of your ~/.bashrc (the first three lines might already be in there):

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

find-up() {
  path=$(pwd)
  while [[ "$path" != "" && ! -e "$path/$1" ]]; do
    path=${path%/*}
  done
  echo "$path"
}

automatic-nvm-use() {
  NVM_PATH=$(find-up .nvmrc | tr -d '[:space:]')

  if [[ $NVM_PATH == $NVM_PATH_WAS ]]; then
    return
  fi

  NVM_PATH_WAS=$NVM_PATH

  if [[ -f "$NVM_PATH/.nvmrc" ]]; then
    nvm use $(<"$NVM_PATH/.nvmrc")
  else
    nvm use default
  fi
}

if [[ "$PROMPT_COMMAND" ]]; then
  export PROMPT_COMMAND="$PROMPT_COMMAND;automatic-nvm-use"
else
  export PROMPT_COMMAND=automatic-nvm-use
fi

Then re-open your terminals, or reinitialize them via source ~/.bashrc.

Note

If your ~/.bashrc contains other code that changes $PROMPT_COMMAND (like making your terminal's title reflect the current directory), make sure it does not simply set a new $PROMPT_COMMAND, but prepends or appends itself. Alternatively, put the above snippet after it.

ZSH

You can use the function provided within the nvm documentation Show archive.org snapshot .

Arne Hartherz
Last edit
Felix Eschey
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2021-06-04 08:32)