How to write a .nvmrc file which automatically change node version

Janani Hariharan picture Janani Hariharan · Jul 19, 2019 · Viewed 21.5k times · Source

Hi I have two projects one in angularjs 4.4.7 and another in angular 6 version. I need to switch between node version for this. I tried using NVM which is working manually. How to handle the version change inside the angularjs program to change the node version when automatically the latest angular page gets loaded. Is there a possible way like that. I went through the #avn also but how to create the .node-version file. Can someone help with any link or correct sample steps

Answer

alexventuraio picture alexventuraio · Sep 8, 2019

As @Aditya-M-P has already mentioned you can run the following command inside your projects root directory to generate the .nvmrc to set a desired NodeJS version for you project to work properly:

node -v > .nvmrc

It will generate something like this inside your .nvmrc file:

v10.16.2

Also using 10.16.2 without the v letter will work just fine.

However, in the official documentation in the .nvmrc section it never mentions that once you get this file created, the specified node version will be loaded automatically. So that's not enough, you need to run the command above so that nvm can look for the .nvmrc file to load the specified version:

nvm use

Here it is a gif for demoing purpose: enter image description here

To autoload the specified node version:

You need to add something else to your shell configuration depending on what you use bash or zsh

To get the exact configuration for each of them, please follow the instructions in the corresponding shell config section.

In my case I'm using zsh so I do need to add this at the end of my .zshrc file and here is the image that confirms it works like a charm:

# place this after nvm initialization!
autoload -U add-zsh-hook
load-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-nvmrc
load-nvmrc

enter image description here

I hope it could be useful for anyone else facing the same question! 😎