Wojciech Brożonowicz
Wojciech Brożonowicz
2 min read

Categories

Tags

NVM!

NVM is node manager, install on linux by (v0.40.1):

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash

Web page of project: https://github.com/nvm-sh/nvm

After install -> restart terminal / editor

Check if running and what version:

nvm --version

Install specific node version f.e. 14:

nvm install 14

List all installed node versions:

nvm ls

Show current used node version:

nvm current

Change node to specific installed version:

nvm use 14

On Linux We can add in project folder file “.nvrmc” and in file just type number of node version that We want to use in our project f.e. 18.

Now in project We can just use command:

nvm use

… and nvm will find version in this file and switch to version 18 (if it is installed)

We can configure bash to do this automatically when enter folder, to do this We have to edit file .bashrc

sudo nano ~/.bashrc

and paste on the end of this file below code:

cdnvm() {
    command cd "$@" || return $?
    nvm_path="$(nvm_find_up .nvmrc | command tr -d '\n')"

    # 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}" | command tail -1 | command tr -d '\->*' | command 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'
cdnvm "$PWD" || exit

Restart terminal / editor and it’s done!!

*INFO: This post is my notes based on Udemy course (“Nextjs 14 od podstaw”) by Jarosław Juszkiewicz