Nodejs Update Version on Cd
One cool feature of rvm is, when you cd
into a directory and you have an .rvmrc
file that contains a valid Ruby version.
I use [nvm] to manage Node.js versions, but it does not offer such functionality.
Currently, if you have an .nvmrc
file, and you type nvm use
it will load the file and change to the version specified in the file. We want to do this automatically.
If you are using zsh
, add this to your .zshrc
:
autoload -U add-zsh-hook
load-nvmrc() {
if [[ -f .nvmrc && -r .nvmrc ]]; then
nvm use
fi
}
add-zsh-hook chpwd load-nvmrc
If you are using bash
, add this to your .bash_profile
:
load_nvmrc() {
if [ "$PWD" != "$PREV_PWD" ]; then
PREV_PWD="$PWD";
if [ -e ".nvmrc" ]; then
nvm use;
fi
fi
}
export PROMPT_COMMAND="$PROMPT_COMMAND load_nvmrc;"
In bash
we make use of PROMPT_COMMAND
:
If set, the value is interpreted as a command to execute before
the printing of each primary prompt ($PS1).