p:: Node, CLI f:: volta

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
nvm install 22
node -v
npm -v
v22.0.0
10.5.1

Set default node version

nvm alias default 20

.nvmrc

You can create a .nvmrc file containing a node version number (or any other string that nvm understands; see nvm --help for details) in the project root directory (or any parent directory). Afterwards, nvm usenvm installnvm execnvm run, and nvm which will use the version specified in the .nvmrc file if no version is supplied on the command line.

echo "18" > .nvmrc

Calling nvm use automatically in a directory with a .nvmrc file

zsh

This shell function will install (if needed) and nvm use the specified Node version when an .nvmrc is found, and nvm use default otherwise.

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:

vim ~/.zshrc
# place this after nvm initialization!
autoload -U add-zsh-hook
 
load-nvmrc() {
  local nvmrc_path
  nvmrc_path="$(nvm_find_nvmrc)"
 
  if [ -n "$nvmrc_path" ]; then
    local nvmrc_node_version
    nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")")
 
    if [ "$nvmrc_node_version" = "N/A" ]; then
      nvm install
    elif [ "$nvmrc_node_version" != "$(nvm version)" ]; then
      nvm use
    fi
  elif [ -n "$(PWD=$OLDPWD nvm_find_nvmrc)" ] && [ "$(nvm version)" != "$(nvm version default)" ]; then
    echo "Reverting to nvm default version"
    nvm use default
  fi
}
 
add-zsh-hook chpwd load-nvmrc
load-nvmrc

After saving the file, run source ~/.zshrc to reload the configuration with the latest changes made.