run `nvm use` automatically every time there's a .nvmrc file on the directory
If you use zsh (z shell):
Calling 'nvm use' automatically in a directory with a .nvmrc file
Put this into your $HOME/.zshrc to call nvm use automatically whenever you enter a directory that contains an .nvmrc file with a string telling nvm which node to use:
# place this after nvm initialization!autoload -U add-zsh-hookload-nvmrc() { local node_version="$(nvm version)" local nvmrc_path="$(nvm_find_nvmrc)" if [ -n "$nvmrc_path" ]; then local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")") if [ "$nvmrc_node_version" = "N/A" ]; then nvm install elif [ "$nvmrc_node_version" != "$node_version" ]; then nvm use fi elif [ "$node_version" != "$(nvm version default)" ]; then echo "Reverting to nvm default version" nvm use default fi}add-zsh-hook chpwd load-nvmrcload-nvmrc
More info: https://github.com/creationix/nvm#zsh
If you use bash you can add this to your ~/.bashrc
file:
enter_directory() { if [[ $PWD == $PREV_PWD ]]; then return fi PREV_PWD=$PWD [[ -f ".nvmrc" ]] && nvm use}export PROMPT_COMMAND=enter_directory
Excellent answer from @devius.
I just extended it so it can revert to the default version when leaving a directory with .nvmrc
to another without it.
~/.bashrc
:
## Run 'nvm use' automatically every time there's # a .nvmrc file in the directory. Also, revert to default # version when entering a directory without .nvmrc#enter_directory() {if [[ $PWD == $PREV_PWD ]]; then returnfiPREV_PWD=$PWDif [[ -f ".nvmrc" ]]; then nvm use NVM_DIRTY=trueelif [[ $NVM_DIRTY = true ]]; then nvm use default NVM_DIRTY=falsefi}export PROMPT_COMMAND=enter_directory
Following @doug-barbieri's suggestion, the script below will not change node back to the default version if there's no .nvmrc
file in the current directory but there is one in the parent sub-directory.
~/.bashrc
:
enter_directory() { if [[ $PWD == $PREV_PWD ]]; then return fi if [[ "$PWD" =~ "$PREV_PWD" && ! -f ".nvmrc" ]]; then return fi PREV_PWD=$PWD if [[ -f ".nvmrc" ]]; then nvm use NVM_DIRTY=true elif [[ $NVM_DIRTY = true ]]; then nvm use default NVM_DIRTY=false fi}
The trick is here:
if [[ "$PWD" =~ "$PREV_PWD" && ! -f ".nvmrc" ]]; then returnfi
It checks if the PWD contains PREV_PWD. For example, if /home/user1/a/b
contains /home/user1/a
.