Skip to content

Instantly share code, notes, and snippets.

@tobiashm
Created July 21, 2022 20:13
Show Gist options
  • Save tobiashm/46d6e6b8d249d5b2f700c69d1a82e698 to your computer and use it in GitHub Desktop.
Save tobiashm/46d6e6b8d249d5b2f700c69d1a82e698 to your computer and use it in GitHub Desktop.
Simple Node.js version manager (based on Homebrew)
# Simple Node.js version manager
#
# Usage example:
# $ use-node 16
#
# The strategy is to identify the Homebrew version, e.g. 'node@16', and the prepend the path to its binaries to $PATH.
# Caveat: This only supports selecting a major version, as that's the level of granularity that Homebrew provides.
use-node() {
if [[ "$1" == "$(node --version | sed 's/v\([0-9]*\).*/\1/')" ]]; then
return 0;
fi
local wanted prefix
wanted=$([[ "$1" == "" ]] && echo "node" || echo "node@$1")
prefix=$(brew --prefix "$wanted" 2> /dev/null)
if [[ "$prefix" == "" ]] || [[ ! -d "$prefix" ]]; then
echo "Node version '$1' not available" >&2
return 1
fi
PATH="$(echo "$PATH" \
| tr ':' '\n' \
| grep -v "${prefix%@*}" \ # remove any previously added Node version paths
| tr '\n' ':')"
if [[ "$1" != "" ]]; then
PATH="$prefix/bin:$PATH"
fi
export PATH
}
# Check for a '.node-version' file every time you enter a new directory.
# The file should contain a single line with a version.
add-zsh-hook -Uz chpwd () {
if [[ -s ".node-version" ]] && command -v use-node > /dev/null; 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