Install Node.js and npm on Ubuntu 22.04

October 14, 2022 · 0 min read
Install Node.js and npm on Ubuntu 22.04
Node.js is a cross-platform JavaScript runtime environment based on Chrome's JavaScript that allows JavaScript code to be executed on the server side. It is commonly used to create back-end applications, but it is also widely used as a full-stack and front-end solution. npm is the world's largest software registry and the default package manager for Node.js.

This tutorial will walk you through 2 different methods for installing Node.js and npm on Ubuntu 22.04:

Install npm and Node.js from the Ubuntu repository.

The Node.js version included in the Ubuntu 22.04 repositories at the time of writing is v16, which is the previous TLS version.
The setup process is fairly simple. To update the package index and install Node.js and npm, run the following commands:

sudo apt update
sudo apt install nodejs npm

The above command will install several packages, including the tools required to compile and install native npm addons.
Once completed, run the following commands to validate the installation:

nodejs --version
v16.0.0

Installing Node.js and npm from NodeSource

NodeSource is a company dedicated to providing enterprise-grade Node support. It keeps an APT repository with multiple Node.js versions. If your application requires a specific version of Node.js, use this repository.
As of this writing, the NodeSource repository offers the following versions:

  • v16.x - The latest stable version.
  • v14.x 

We’ll install Node.js version 16.x:

To download and run the NodeSource installation script, run the following command as a sudo user

curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -

The script will add the NodeSource signing key to your system, create an apt repository file, install all necessary packages, and refresh the apt cache.

If you need another Node.js version, for example 12.x, change the setup_14.x with setup_12.x.

Install Node.js and npm after enabling the NodeSource repository:

sudo apt install nodejs

The nodejs package contains both the node and npm binaries.

Verify that the Node.js and npm were successfully installed by printing their versions:

node --version
v16.0.0
npm --version
6.14.4

To be able to compile native addons from npm you’ll need to install the development tools:

sudo apt install build-essential

Conclusion

We demonstrated 2 methods for installing Node.js and npm on your Ubuntu 20.04 server. The method you select is determined by your needs and preferences. Although installing the packaged version from the Ubuntu or NodeSource repositories is simpler, the nvm method allows you to add and remove different Node.js versions on a per-user basis.