Node.js is a popular runtime environment for executing JavaScript code on the server side. Developers often need to switch between different Node.js versions to match project requirements. The Node Version Manager (nvm) is a handy tool that makes this process seamless. In this blog post, we’ll explore how to change Node.js versions using nvm.
Prerequisites
Before we get started, ensure that you have nvm installed on your system. If you don’t have it installed, you can follow the steps below:
- Install nvm on macOS/Linux:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.5/install.sh | bash
- Install nvm on Windows: On Windows, you can use nvm-windows, which is a separate project. Download the installer from nvm-windows GitHub and follow the instructions.
Once nvm is installed, restart your terminal and verify the installation:
nvm –version
Checking Installed Node.js Versions
To see the Node.js versions currently installed on your system, run:
nvm ls
This will list all the installed versions and indicate the active one with an arrow (->
).
Listing Available Node.js Versions
To check all the available Node.js versions that can be installed, use:
nvm ls-remote
This command fetches a list of all Node.js versions from the official repository.
Installing a Specific Node.js Version
To install a specific Node.js version, run:
nvm install <version>
For example, to install Node.js version 16.14.0:
nvm install 16.14.0
Using a Specific Node.js Version
Once the desired version is installed, you can switch to it with:
nvm use <version>
For example:
nvm use 16.14.0
After switching, you can confirm the active version by running:
node -v
Setting a Default Node.js Version
If you frequently use a specific version, you can set it as the default:
nvm alias default <version>
For example:
nvm alias default 16.14.0
This ensures that the specified version is automatically used in new terminal sessions.
Uninstalling a Node.js Version
To remove a Node.js version you no longer need, run:
nvm uninstall <version>
For example:
nvm uninstall 14.17.0
Troubleshooting Common Issues
- Command not found: Ensure nvm is properly installed and its script is sourced in your shell configuration file (e.g.,
.bashrc
,.zshrc
, or.bash_profile
). - Permission issues: Ensure that nvm directories have the appropriate permissions. Avoid using
sudo
with nvm commands. - PATH conflicts on Windows: Ensure no other Node.js installations (e.g., via the Node.js installer) interfere with nvm.
Using nvm to manage Node.js versions is a game-changer for developers who work on multiple projects. It simplifies the process of installing, switching, and maintaining Node.js versions. With the steps outlined above, you’re now equipped to manage Node.js versions like a pro.