A better 'cd' for JS nvm users - Gandalf's Blog

โ† All posts

โ€‹ - โ€‹

A better 'cd' for JS nvm users

#javascript

nvm's official script for automatically switching node version while cd'ing into different projects is very slow. Every invocation of cd takes a long time regardless of whether a new project is reached. A speedy alternative has been proposed in nvm's github issues, and it works fine.

Copying from github issue #3508, the following is the proposed script that can be placed in .bashrc:
bash
cdnvm() {
    command cd "$@" || return $?
    eval $(bash <<'END'
        dir=$(pwd)
        while true; do
            if [ -f "$dir/.nvmrc" ]; then
                current_v=$(node -v | sed 's/^v//; s/[[:space:]]*$//')
                this_v=$(cat "$dir/.nvmrc" | sed 's/^v//; s/[[:space:]]*$//')
                
                if [ "$this_v" != "$current_v" ]; then
                    echo "nvm use"
                fi
                break
            fi
            
            if [ "$dir" = "/" ]; then
                break
            fi
            
            dir=$(dirname "$dir")
        done
END
    )
}

alias cd='cdnvm'
cdnvm "$PWD" || exit