Installing Node.js can be accomplished through various methods. In my recent experience with a project hosted in an organization’s repository, I encountered the need to work with different Node.js versions.
Fortunately, Node Version Manager (NVM) proved to be an invaluable tool in this scenario, allowing seamless switching between Node.js versions on demand. Additionally, NVM facilitates code testing with older Node.js versions.
This step is discretionary; skip it if you haven’t previously installed Node.js using Homebrew.
If there’s an existing Node.js version on your machine, it’s advisable to remove it before installing NVM. For instance, if you’ve installed Node.js via Homebrew, open the terminal and execute the following commands:
brew uninstall --ignore-dependencies nodebrew uninstall --force node
brew install nvm
Once the installation is complete, create a directory for NVM in the home working directory:
mkdir ~/.nvm
For users of the zsh shell, insert the following configuration inside ~/.zshrc:
export NVM_DIR="$HOME/.nvm"[ -s "/opt/homebrew/opt/nvm/nvm.sh" ] && \. "/opt/homebrew/opt/nvm/nvm.sh" # Load nvm[ -s "/opt/homebrew/opt/nvm/etc/bash_completion.d/nvm" ] && \. "/opt/homebrew/opt/nvm/etc/bash_completion.d/nvm" # Load nvm bash_completion
After making these changes, restart the terminal app or execute source ~/.zshrc to reload the latest configuration.
Verify the NVM installation by running:
nvm -v
Node.js is available in two versions: Long Term Support (LTS) and Current with the latest features. To install the current LTS Node.js version, run:
nvm install --lts
Verify the installed version:
node -v
Managing Multiple Node.js Versions:
Install different Node.js versions using:
nvm install Version-Number
nvm install 21.5.0
Set a specific Node.js version as the default:
nvm use 18.17.0
Uninstall a Node.js version:
Ensure the version isn’t active, then run:
nvm uninstall 21.5.0
List all installed Node.js versions:
nvm ls
Set the latest Node.js version as the default:
nvm alias default node
To install yarn, simply run
npm install --global yarn
To confirm it worked, run below command. if that works, you’re good to go!
yarn -v