Node version management with NVM
Node Version Manager (NVM) is a powerful tool that allows developers to manage multiple versions of Node.js on a single machine. This flexibility is crucial when working on different projects that require specific Node.js versions. In this blog post, we'll walk through the process of installing NVM on macOS using Homebrew.
Prerequisites
Before we begin, ensure that you have Homebrew installed on your macOS. If you don't have it yet, you can install it by running the following command in your terminal:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Step-by-Step Installation Guide
1. Uninstall Previous Node.js Versions
If you have any previous versions of Node.js installed via Homebrew, it's best to uninstall them first:
brew uninstall node
# Or, for a forceful uninstallation:
brew uninstall --force node
2. Install NVM using Homebrew
Now, let's install NVM using Homebrew:
brew install nvm
3. Create NVM Directory
Create a directory for NVM to store different versions of Node.js:
mkdir ~/.nvm
4. Configure Shell Profile
We need to add NVM configuration to your shell profile. If you're using Zsh (default in recent macOS versions), edit your ~/.zshrc file:
nano ~/.zshrc
Add the following lines to the file:
export NVM_DIR="$HOME/.nvm"
# This loads nvm
[ -s "/usr/local/opt/nvm/nvm.sh" ] && \. "/usr/local/opt/nvm/nvm.sh"
# This loads nvm bash_completion
[ -s "/usr/local/opt/nvm/etc/bash_completion.d/nvm" ] && \. "/usr/local/opt/nvm/etc/bash_completion.d/nvm"
5. Apply Changes
To apply the changes made to your shell profile, run:
source ~/.zshrc
6. Verify NVM Installation
Check if NVM is installed correctly by running:
nvm --version
Installing Node.js with NVM
Now that NVM is installed, you can easily manage different Node.js versions:
-
To install the latest Node.js version:
nvm install node
-
To install the Long Term Support (LTS) version:
nvm install --lts
-
To use the LTS version:
nvm use --lts
-
To list installed Node.js versions:
nvm ls
Troubleshooting: NVM with Oh My Zsh
If you install Oh My Zsh after setting up NVM, it might interfere with your NVM path. To fix this, add the following lines at the very top of your ~/.zshrc file:
export NVM_DIR=~/.nvm
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
After making these changes, don't forget to run:
source ~/.zshrc
Congratulations! You've successfully installed NVM on your macOS system. Now you can easily switch between different Node.js versions as needed for your projects.
🥳 Happy coding!