header image

Code Snippets

Zsh - Auto Select Node Version

| Last updated:
# n auto select nodejs version hook
autoload -U add-zsh-hook
select-node-version() {
    if [[ -f .nvmrc && -r .nvmrc ]] || \
        [[ -f .node-version && -r .node-version ]] || \
        [[ -f .n-node-version && -r .n-node-version ]] || \
        [[ -f package.json && -r package.json ]]; then
        n auto -q &>/dev/null
        local change=$?
    elif [[ ! $(node -v) =~ $(n --lts) ]]; then
        n lts -q &>/dev/null
        local change=$?
    fi
    if [[ $change ]]; then
        echo "Node $(node -v)"
    fi
}
add-zsh-hook chpwd select-node-version
select-node-version

Automatically Select NodeJS Version in Zsh Shell using 'n'

Install n

Install n NodeJS version manager ensuring it is a local install for user, so it doesn’t require sudo.

For example, on linux distros:

curl -L https://git.io/n-install | bash

Add Script

Append the above code snippet to your .zshconfig file, making sure it is after the 'n' setup commands which are added during install.

The script will:

  • Add a hook to check for node version config file in the current directory after each dir change. If:
    • Config file present - 'n' will attempt to auto install and switch to the required node version
    • No config file - 'n' will switch to current NodeJS lts if it is not already the current version

Notes

  • Assumes you are using Zsh shell