Install and Run Different NodeJS Versions with NVM

Overview

In this tutorial, you will be shown how to use NVM to install and run different NodeJS versions, as well as, how to select the correct versions for your app when multiple NodeJS versions are available.

Whether you have a build server for multiple NodeJS projects or you are running multiple NodeJS apps on the same production server, it is very unlikely all projects will be based on the same NodeJS version.

Ensuring your application is available and reliable once in production is

Installing NVM

NVM is typically installed via a wget or curl command. The command will automatically detect your Linux or OSX version, and install the appropriate release.

Install NVM using curl

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

Install NVM using wget

wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash

After the NVM installation process is complete you can verify its status by running the following command.

command -v nvm

Which will output the following if installation was successful.

nvm

Installing NodeJS using NVM

With NVM installed we can begin installing and managing NodeJS versions. To install NodeJS we use the nvm install command with the release version of NVM we want to be installed.

For example, to install the latest version of NodeJS you would just specify node as the version.

nvm install node

Alternatively, you would specify the release version instead.

nvm install 8.0.0

When you install a new version of node onto your server, the previous versions will not be removed. This is what allows us to run multiple versions on the same host.

Managing Installed NodeJS Versions

To list the versions of node installed on your server you use the nvm ls command. In the example below, you will notice an arrow pointing to one of the versions, which means the version is the active one for the user environment.

nvm ls

     v8.0.0    v10.15.3
 ->      v12.2.0
          system
 default -> 8.0.0 (-> v8.0.0)
 node -> stable (-> v12.2.0) (default)
 stable -> 12.2 (-> v12.2.0) (default)
 iojs -> N/A (default)
 unstable -> N/A (default)
 lts/* -> lts/dubnium (-> v10.15.3)
 lts/argon -> v4.9.1 (-> N/A)
 lts/boron -> v6.17.1 (-> N/A)
 lts/carbon -> v8.16.0 (-> N/A)
 lts/dubnium -> v10.15.3

To switch to a different version of Node, we use the the nvm use command with the version of node we desire.

nvm use v8.0.0

Set NodeJS Version in Application Project

Now that you have a number of NodeJS versions installed on your system, how do you specify which one your application should use? You will need to create an .nvmrc file in your project root.

In the .nvmrc file, we specify the version of Node the project requires, as well as any additional nvm flags.

The following is an example .nvmrc file

v8.0.0

With a .nvmrc file in place, the Node version can be selected simply by running the npm use command without any arguments.