Skip to content

Instantly share code, notes, and snippets.

@mudge
Created August 26, 2019 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mudge/7d45e9c664d416f47369bc806a9e3bce to your computer and use it in GitHub Desktop.
Save mudge/7d45e9c664d416f47369bc806a9e3bce to your computer and use it in GitHub Desktop.
Auto-switch Node.js versions with chnode by reading .node-version files
# Based off chruby's auto.sh: https://github.com/postmodern/chruby#auto-switching
unset NODE_AUTO_VERSION
function chnode_auto() {
local dir="$PWD/" version
until [[ -z "$dir" ]]; do
dir="${dir%/*}"
if { read -r version <"$dir/.node-version"; } 2>/dev/null || [[ -n "$version" ]]; then
if [[ "$version" == "$NODE_AUTO_VERSION" ]]; then return
else
NODE_AUTO_VERSION="$version"
chnode "$version"
return $?
fi
fi
done
if [[ -n "$NODE_AUTO_VERSION" ]]; then
chnode_reset
unset NODE_AUTO_VERSION
fi
}
if [[ -n "$ZSH_VERSION" ]]; then
if [[ ! "$preexec_functions" == *chnode_auto* ]]; then
preexec_functions+=("chnode_auto")
fi
elif [[ -n "$BASH_VERSION" ]]; then
trap '[[ "$BASH_COMMAND" != "$PROMPT_COMMAND" ]] && chnode_auto' DEBUG
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment