Nvm

1 item

Jé pa l'temps #14 - Autoload correct Node.js version with nvm

These two scripts allows you to tell to your shell to autodetect .nvmrc in your Node.js projects and to load the wanted Node.js version.

With Bash

# Run 'nvm use' automatically every time there's 
# a .nvmrc file in the directory. Also, revert to default 
# version when entering a directory without .nvmrc
#
enter_directory() {
if [[ $PWD == $PREV_PWD ]]; then
  return
fi

PREV_PWD=$PWD
if [[ -f ".nvmrc" ]]; then
  nvm use
  NVM_DIRTY=true
elif [[ $NVM_DIRTY = true ]]; then
  nvm use default
  NVM_DIRTY=false
fi
}

export PROMPT_COMMAND=enter_directory

With ZSH

# place this after nvm initialization!
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

— — — — — — — — — — — — — — — — — — — — —

La série « Jé pa l’temps » est une série de tutoriels rapides en mode “prise de note” pour avoir une trace de tout ce dont je ne peux me rappeler et pourquoi pas le partager à d’autre. On va à l’essentiel, laissons les jolis pavés à d’autres sites comme medium… LOL !

Read more →
jplt Node.js