Sep28

Tired of managing Node.js versions? NVM can help!

I remembered when I first learned JavaScript, I still use Node.js provided in Ubuntu. That brought me to some problems down the road.

Sometimes, I need sudo every time I want to install NPM packages globally. And sometimes, I can't have two or more Node.js versions for apps that depend on different versions of Node.js.

Heck, how should I do then?

Worry not, there is nvm!

Well -- it's not "nevermind", but Node Version Manager.

This package is wonderful. It helps you fetch and install Node.js, and also can manage which version of Node.js I want to use.

But more importantly, after Node.js is installed through NVM, I can install Node.js packages globally without having to use sudo.

Neat.

The installation is pretty straightforward: I follow the instructions provided in their GitHub page (or straight to the installation section to install right away).

To update, I just need to run the same command as I install NVM for the first time.

Then, after the installation is done, I re-open the terminal for changes to take effect (or you can run the script provided by NVM after installation is complete).

And, once that's done, I run nvm install followed by the version of Node.js that I want to install.

BUT first of all, we might want to uninstall Node.js installed through distro repos first. If you don't have Node.js installed through your distro package manager like apt or pacman, you can skip this step.

The uninstall might depend on which distro you're using, so you might want googling it first. I use Ubuntu here, so sudo apt purge node.js applies here.

To install the latest version of Node.js:

nvm install latest

To install the LTS version:

nvm install lts

Switching from one version to another is pretty straightforward, too. I can just run nvm use command, followed by the version of Node.js that I want to use, just like above.

But remember, switching versions doesn't mean the installed NPM packages got moved too. You might want to also re-install the missing packages after switching.

Voila! Now to make sure that Node.js is working, we can run npm -v and node -v commands. If we see the following:

$ npm -v
6.14.11

$ node -v
v14.16.0

Then we successfully installed Node.js through NVM!

What about Windows?

If you use Windows, you can use an alternative repo provided by @coreybutler here.

Its installation progress is different as it uses installer package, rather than the command line. After the installation is complete, run Command Prompt or PowerShell in Administrator mode, and you can run nvm like I did above!

Bottom line

I honestly like to use NVM, as it's simpler, and doesn't require me to use sudo to install NPM packages globally. Also, while it's now limited to user-level scope, it doesn't affect me that much -- moreover, I only use 1 user in each OS I use.

But anyways, I hope that this will help you!