Feb 01, 2023

Manage Multiple Node.js Versions With Homebrew

Manage Multiple Node.js Versions With Homebrew

Homebrew is a free and open-source software package management system that simplifies the installation of binaries and graphical applications on MacOS.

In this article, you'll learn how to install multiple versions of Node.js locally using Homebrew and how to easily switch between them.

Listing the available Node.js versions

To list the available versions of Node.js, you can use the brew search command:

$ brew search node
node ✔    node@10    node@12    node@14    node@16    node@18

That will also show you which versions are already installed on your system — which are the ones marked with a checkmark.

Installing a specific Node.js version

To install a specific Node.js version, you can use the brew install command:

$ brew install node@<version>

That will download the specified version in the /usr/local/Cellar directory.

$ ls /usr/local/Cellar
node   node@16

And create a symbolic link to the binary file of the version you just downloaded in the /usr/local/opt directory.

$ ls -l /usr/local/opt
lrwxr-xr-x  1 admin  admin  21 Feb  1 11:33 node -> ../Cellar/node/19.5.0
lrwxr-xr-x  1 admin  admin  27 Feb  1 11:32 node@16 -> ../Cellar/node@16/16.19.0_1

Defining aliases

To be able to switch between the different Node.js version installed on your system, you can create an alias in your .zshrc file if you're using ZSH or .bash_profile if you're using Bash:

# Open ZSH configuration with Vim
$ vim ~/.zshrc

# Open Bash configuration with Vim
$ vim ~/.bash_profile

That will reference the symbolic link of the Node.js version you want to use:

alias node16="/usr/local/opt/node@16/bin/node"

Once you've added this line, you can save and quit the configuration file, and load it using the source command:

# Load ZSH configuration
$ source .zshrc

# Load Bash configuration
$ source .bash_profile

Switching between versions

You can now either use the default node binary (which is usually the latest version):

$ node -v
v18.13.0

Or use one of the specific versions you defined an alias for:

$ node16 -v
v16.19.0

Et voilà!