Skip to content

Instantly share code, notes, and snippets.

@matheusfaustino
Created June 16, 2022 09:43
Show Gist options
  • Save matheusfaustino/db6d02b45d44605953bc3ccd4c4ac402 to your computer and use it in GitHub Desktop.
Save matheusfaustino/db6d02b45d44605953bc3ccd4c4ac402 to your computer and use it in GitHub Desktop.
Zsh function to change nodeJS version per project (directory) using NVM
# Add at the end of your .zshrc file
# After every command `cd`, it checks if there is a ".nvmrc" file in the current directory and if it exists it changes the version of nodejs automatically
# Create a .nvmrc file like this: `echo "v16.15.0" > .nvmrc` in the folder you want to use the specific version of nodejs
function nvm_change_by_dir() {
emulate -L zsh
if [ -f ".nvmrc" ]; then
NODEJS_VERSION=$(cat .nvmrc);
COMMAND="nvm use"
if [ $(node --version) != $NODEJS_VERSION ]; then
eval "$COMMAND";
fi
fi
}
# hook function
chpwd_functions=(${chpwd_functions[@]} "nvm_change_by_dir")
# run command when open a new shell session
nvm_change_by_dir
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment