Installing NodeJS in a development environment: The right way
First appeared on Stackrole · Updated
Working on projects that use different versions of Node.js, and having trouble getting them to run? Then you need a version manager. My pick in 2020 was nvm (Node Version Manager), and it is still a solid choice.
Install nvm
nvm installs with one command from its README. Copy it from the nvm README so you get the latest version; my 2020 post pinned v0.35.3, which is long out of date. It looks like this:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/<latest-version>/install.sh | bash
The script adds a few lines to your shell profile (~/.zshrc on macOS, or ~/.bashrc, ~/.bash_profile or ~/.profile) that load nvm in every new terminal. Close and reopen the terminal, or reload the profile in the same window:
source ~/.zshrc
Install Node.js
nvm install --lts # the current long-term support version
nvm install 22 # or a specific major version
In 2020 I used nvm install 12; Node 12 reached end of life in 2022. Installing with --lts avoids picking an outdated version by accident.
Each version gets its own npm and its own global packages, so switching versions never breaks another project's setup.
Switch versions
nvm use 22
nvm ls # list installed versions
nvm alias default 22 # the version new terminals start with
Switch automatically per project
It is easy to forget which version a project needs. Record it in a .nvmrc file at the project root:
node -v > .nvmrc
Then nvm use, with no version, reads the file. To make it run automatically whenever you cd into the folder, add the load-nvmrc hook from the nvm README to your ~/.zshrc.
In 2020 I used a separate tool for this, avn, with a .node-version file. avn is no longer maintained, so I would skip it now.
Faster alternatives
nvm is a shell script, which makes new terminals a little slower to open. If that bothers you: