Skip to content

Instantly share code, notes, and snippets.

@tobiashm
Last active November 2, 2018 13:39
Show Gist options
  • Save tobiashm/da3aba3071c826c742bb02e2ad0d14ba to your computer and use it in GitHub Desktop.
Save tobiashm/da3aba3071c826c742bb02e2ad0d14ba to your computer and use it in GitHub Desktop.
Switch Node.js version with Homebrew
# Assumes you have installed individual major versions with Homebrew, like node@8,
# this command allows you to switch by calling e.g. `use-node 8`, or to get the
# current latest version (`brew install node`) if you don't pass an argument.
# Notice: Since it modifies the env, this will only work for the current session.
# I.e. other terminal windows will have the default Node version, unless they’re also changed.
use-node() {
wanted=$([ "$1" == "" ] && echo "node" || echo "node@$1")
prefix=$(brew --prefix $wanted 2> /dev/null)
if [ "$prefix" != "" ]; then
PATH="$(echo $PATH | tr ':' '\n' | grep -v ${prefix%@*} | tr '\n' ':')"
if [ "$1" != "" ]; then PATH="$prefix/bin:$PATH"; fi
export PATH
else
echo "Node version '$1' not available"
fi
}
@tobiashm
Copy link
Author

tobiashm commented Nov 2, 2018

Auto-use a specified version when changing dir; put the following in your .profile or .bashrc:

cd() {
  builtin cd "$@" || return

  if [ -f ".node-version" ]; then
    use-node $(cat .node-version)
  fi
}

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