Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cesalazar
Last active December 7, 2021 22:44
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 cesalazar/976163e198985d0d5912eb6512126ba8 to your computer and use it in GitHub Desktop.
Save cesalazar/976163e198985d0d5912eb6512126ba8 to your computer and use it in GitHub Desktop.
Automatically changes NodeJS version using `n` node package in zsh
# hooks onto `chpwd` with the official util `add-zsh-hook`
# `export N=false` to disable auto-switching versions
function auto-switch-node-version() {
# track if the version changed
local changed=false
# exit early
[[ ${N} == false || ! $(command -v n) ]] && return
# attempt to change the version based on the "engine" entry in package.json
n engine &>/dev/null && changed=true
# fallback to .nvmrc file if it exists
[[ ${changed} == false && -f .nvmrc ]] && n auto &>/dev/null && changed=true
# give up and write a log if the folder is a node project :(
[[ ${changed} == false && -f package.json ]] && printf "%s\n" \
"Missing \"engine\" entry in package.json" \
"File .nvmrc not found" \
"Falling back to node $(node -v) and npm v$(npm -v)" \
>! n.log
}
# switch node version automatically on new session
auto-switch-node-version
# load add-zsh-hook if it's not available yet
(( $+functions[add-zsh-hook] )) || autoload -Uz add-zsh-hook
# hook auto-switch-node-version onto `chpwd`
add-zsh-hook chpwd auto-switch-node-version
# list existing hook functions
# add-zsh-hook -L
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment