pez
pez

Reputation: 1149

Set node version with NVM or install if not available.

I'm trying to add to my bash profile something that will set my node version to a specific version, and if the node version is not installed then install it. What I have so far is:

. /usr/local/opt/nvm/nvm.sh
if [[ $(nvm use v6.9.1) == "" ]]; then
  nvm install v6.9.1
fi

However, the problem is that the $(nvm use v6.9.1) is run in a subshell and my node version doesn't get switched.

a) Is there any way to have $(nvm use v6.9.1) run in the current shell?

b) Is there a better way of doing this?

Previously I was just running nvm install v6.9.1 but this was kinda slow which was an issue as it runs each time I open a new terminal.

Thanks Matt!

Upvotes: 2

Views: 4169

Answers (4)

joeytwiddle
joeytwiddle

Reputation: 31285

In the current version of nvm, nvm install does not reinstall node if it's already installed.

Examples:

$ nvm install v16.0.4
v16.14.2 is already installed.

# The same if you have put the version in your project's .nvmrc
$ nvm install
v16.0.4 is already installed.

Note however, if you specify an ambiguous version such as v16 and a newer version of v16 is available, then nvm will download and install the newer version, ignoring your older version of v16.

$ node --version
v16.0.4
$ nvm install v16
Downloading and installing node v16.14.2...

So specifying v16 is good if you always want to be up-to-date, and have the latest security patches. But eventually you might end up with lots of versions of node installed!

To keep just one version installed (to save disk space, or to keep packages you previously installed globally with npm) then specify the full version v16.0.4.

Upvotes: 1

Chris Crewdson
Chris Crewdson

Reputation: 1480

I have a bash alias I use for this that works for multiple versions:

alias nvmuse='nvm use || nvm install $(cat .nvmrc)'

Upvotes: 6

wrkwrk
wrkwrk

Reputation: 2351

This works. If use failed, it will execute install.

#!/bin/sh

nvm use 14.18.1 || nvm install 14.18.1

# or if you don't need the warning
nvm use 14.18.1 2>/dev/null || nvm install 14.18.1

execute example

Upvotes: -1

Renato Gama
Renato Gama

Reputation: 16519

Have you tried grepping nvm ls?

. /usr/local/opt/nvm/nvm.sh
if [[ $(nvm ls | grep v6.9.1) == "" ]]; then
  nvm install v6.9.1
else
  nvm use v6.9.1
fi

Is it any faster than using nvm install v6.9.1 for you?

EDIT: You can also set a default version that will always be loaded by default. You can do it by running nvm alias default 6.9.1.

You can try changing your script to this:

if [[ $(node -v) != "v6.9.5" ]]; then
  nvm install v6.9.5
  nvm alias default v6.9.5
fi

It will take a little long, but just for the first time

Upvotes: 3

Related Questions