28
votes

Let's say I have 2 projects:

example1: requires node version 0.12.1
example2: requires node version 0.10

Currently, when I cd into each project, I use nvm use <version> before running the application.

Is there a way with node or nvm, to automatically switch to the needed version of node when I cd into each project?

7
Doubt it. You could however have a npm run that does it.Kevin B
You could setup a bash script and call from there. PlausibleNaing Lin Aung

7 Answers

14
votes

Install Automatic Node Version Switching (avn) and add .node-version file that specifies the version you'd like to use with project. It automatically detects and uses it via installed version manager such as nvm and n.

9
votes

You can add nvm command into package.json file

"scripts": {
  "preinstall": "nvm install 0.12.1",
  "prestart": "nvm use 0.12.1",
  "start": "node ./file1.js"
},

Also set desired version into package.json, so Continuous Integration services would know what version you want to use.

{
  "name": "naive",
  "description": "A package using naive versioning",
  "author": "A confused individual <[email protected]>",
  "dependencies": {
    "express": ">= 1.2.0",
    "optimist": ">= 0.1.0"
  },
  "engine": "node 0.4.1"
}
7
votes

Looks for a .nvmrc file in your current directory, every time you cd. If one is found, it loads the version via nvm use and throws out any output.

cd() {
  builtin cd "$@"
  if [[ -f .nvmrc ]]; then
    nvm use > /dev/null
  fi
}
cd .
4
votes

NPM now let's you specify the node version for a project like this npm install node@8.

So next time you do a npm ci or npm i, the correct version is automatically set.

1
votes

There are also extended (user contributed) bash/zsh shell scripts in the NVM GitHub README:

bash script

Automatically call nvm use
This alias would search 'up' from your current directory in order to detect a .nvmrc file. If it finds it, it will switch to that version; if not, it will use the default version.

Put the following at the end of your $HOME/.bashrc:

find-up () {
    path=$(pwd)
    while [[ "$path" != "" && ! -e "$path/$1" ]]; do
        path=${path%/*}
    done
    echo "$path"
}

cdnvm(){
    cd "$@";
    nvm_path=$(find-up .nvmrc | tr -d '[:space:]')

    # If there are no .nvmrc file, use the default nvm version
    if [[ ! $nvm_path = *[^[:space:]]* ]]; then

        declare default_version;
        default_version=$(nvm version default);

        # If there is no default version, set it to `node`
        # This will use the latest version on your machine
        if [[ $default_version == "N/A" ]]; then
            nvm alias default node;
            default_version=$(nvm version default);
        fi

        # If the current version is not the default version, set it to use the default version
        if [[ $(nvm current) != "$default_version" ]]; then
            nvm use default;
        fi

        elif [[ -s $nvm_path/.nvmrc && -r $nvm_path/.nvmrc ]]; then
        declare nvm_version
        nvm_version=$(<"$nvm_path"/.nvmrc)

        declare locally_resolved_nvm_version
        # `nvm ls` will check all locally-available versions
        # If there are multiple matching versions, take the latest one
        # Remove the `->` and `*` characters and spaces
        # `locally_resolved_nvm_version` will be `N/A` if no local versions are found
        locally_resolved_nvm_version=$(nvm ls --no-colors "$nvm_version" | tail -1 | tr -d '\->*' | tr -d '[:space:]')

        # If it is not already installed, install it
        # `nvm install` will implicitly use the newly-installed version
        if [[ "$locally_resolved_nvm_version" == "N/A" ]]; then
            nvm install "$nvm_version";
        elif [[ $(nvm current) != "$locally_resolved_nvm_version" ]]; then
            nvm use "$nvm_version";
        fi
    fi
}
alias cd='cdnvm'

zsh script

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-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
0
votes

If you're using a Bash shell, you can define a Bash alias to cd, which will do nvm install / nvm use for you when it detects a .nvmrc file.

alias cd='function cdnvm(){ cd $@; if [[ -f .nvmrc ]]; then <.nvmrc nvm install; fi; };cdnvm'

If you want to make the Node version to revert back to the default when you cd out of the directory, use the following alias:

alias cd='function cdnvm(){ cd $@; if [[ -f .nvmrc && -s .nvmrc  && -r .nvmrc ]]; then <.nvmrc nvm install; elif [[ $(nvm current) != $(nvm version default) ]]; then nvm use default; fi; };cdnvm'
0
votes

If you're fine with using another tool you could use nvshim.

pip install nvshim  # this is all you need to do

It does not slow your shell start up, instead moving the lookup of which node version to when you call node, npm or npx by shimming those binaries. More details in the docs.

Source, I wrote the tool.