Skip to content

Instantly share code, notes, and snippets.

@rockaBe
Last active June 16, 2023 10:09
Show Gist options
  • Save rockaBe/ad1e2556f84c7b8807acdd2e09063ee0 to your computer and use it in GitHub Desktop.
Save rockaBe/ad1e2556f84c7b8807acdd2e09063ee0 to your computer and use it in GitHub Desktop.
Auto loading node version using fnm from .nvmrc or .node-version file in the current folder
# ZSH
autoload -U add-zsh-hook
# place default node version under $HOME/.node-version
load-nvmrc() {
DEFAULT_NODE_VERSION=`cat $HOME/.node-version`
if [[ -f .nvmrc && -r .nvmrc ]] || [[ -f .node-version && -r .node-version ]]; then
fnm use
elif
[[ `node -v` != $DEFAULT_NODE_VERSION ]]; then
echo Reverting to node from "`node -v`" to "$DEFAULT_NODE_VERSION"
fnm use $DEFAULT_NODE_VERSION
fi
}
add-zsh-hook chpwd load-nvmrc
load-nvmrc

Uninstall avn and nvm

Uninstall and remove nvm references

brew uninstall nvm rm -rf ~/.nvm

comment / remove references in ~/.zshrc

# export NVM_DIR="{$HOME}/.nvm"
# [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"  # This loads nvm

Uninstall and remove avn references

npm uninstall -g avn rm -rf ~/.avn rm ~/.avnrc

comment / remove references in ~/.zshrc

# [[ -s "$HOME/.avn/bin/avn.sh" ]] && source "$HOME/.avn/bin/avn.sh" # load avn

Use fnm with a homebaked script

install fnm

brew install Schniz/tap/fnm

create a default .node-version file in your users $HOME folder

echo '14.5.0' > ~/.node-version

use auto-node-version-switch.sh in .zshrc

source /path/to/auto-node-version-switch.sh
@georgiosgiatsidis
Copy link

georgiosgiatsidis commented Jun 16, 2023

Here is my updated script cause I don't want to place the default version in a file. Hope it helps. It also installs the required version if not found.

# ZSH
autoload -U add-zsh-hook

load-nvmrc() {
  DEFAULT_NODE_VERSION="$(fnm ls | awk '/default/{print $2}')"
  CURRENT_NODE_VERSION="$(fnm current)"
  REQUIRED_NODE_VERSION=""

  if [[ -f .nvmrc && -r .nvmrc ]]; then
    REQUIRED_NODE_VERSION="$(cat .nvmrc)"

    if [[ $CURRENT_NODE_VERSION != $REQUIRED_NODE_VERSION ]]; then
      echo "Reverting to node from \"$CURRENT_NODE_VERSION\" to \"$REQUIRED_NODE_VERSION\""

      if fnm ls | grep -q $REQUIRED_NODE_VERSION; then
        fnm use $REQUIRED_NODE_VERSION
      else
        echo "Node version $REQUIRED_NODE_VERSION not found. Installing..."
        fnm install $REQUIRED_NODE_VERSION
        fnm use $REQUIRED_NODE_VERSION
      fi
    fi
  else
    if [[ $CURRENT_NODE_VERSION != $DEFAULT_NODE_VERSION ]]; then
      echo "Reverting to default node version: $DEFAULT_NODE_VERSION"
      fnm use $DEFAULT_NODE_VERSION
    fi
  fi
}

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment