How to Install Node.js and npm on Ubuntu (2024 Guide)

Ubuntu tutorial - IT technology blog
Ubuntu tutorial - IT technology blog

Why Do Developers Need Node.js and npm?

Finished setting up your Ubuntu server, now what? For web developers, especially in the JavaScript world, the answer is almost certainly Node.js and npm.

Fundamentally, Node.js shatters the limits of JavaScript. It allows you to run JavaScript code directly on the server, no browser required. This enables you to build the entire backend, from APIs for mobile apps to complex microservices, using just a single language. And npm (Node Package Manager) is its trusted sidekick, a package manager that helps you install, share, and manage millions of available code libraries.

In short, you’ll need them to:

  • Build server-side applications (e.g., APIs for a React Native app, backend for a Next.js website).
  • Use modern frontend build tools like Vite and Webpack. For example, the `npm run build` command you often use runs thanks to Node.js.
  • Run automation scripts during the development process.

When starting with Node.js, you’ll find there are several ways to install it. Much like choosing between `apt` on Ubuntu or `yum` on CentOS, each method has its own philosophy. Choosing the right way from the start will save you a lot of trouble later, especially version conflict errors.

3 Common Ways to Install Node.js and npm

Below are the three most common methods. I’ll go from the most flexible method favored by professional developers to the simplest one that’s less commonly used in production environments.

Method 1: Using NVM (Node Version Manager) – The Most Flexible Way

NVM is a tool that helps you manage multiple Node.js versions on the same machine. This is a lifesaver when you’re working on multiple projects, each requiring a different Node version. For example, project A runs on Node 18 (LTS) while project B needs Node 20 to use a new feature. NVM lets you switch between them with a single command.

Step 1: Install NVM

Open your terminal and run the NVM installation script. You should check the official NVM GitHub page to get the installation command for the latest version, as it ensures you have the latest patches and features.

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

Afterward, you need to either restart your terminal or run the command below for the terminal to “recognize” NVM.

export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

Step 2: Verify the NVM Installation

To make sure NVM is ready, type the command:

command -v nvm

If the terminal returns `nvm`, you’ve succeeded.

Step 3: Install a Node.js Version

With NVM, installing Node.js is extremely intuitive. To install the latest LTS (Long-Term Support) version, which is the stable version recommended for most projects:

nvm install --lts

Or if your project requires a specific version, for example `18.17.0`:

nvm install 18.17.0

Step 4: Select the Node.js Version to Use

After installing, you need to “tell” NVM to use that version for the current session:

nvm use 18.17.0

To set a version as the default every time you open a new terminal, use the command:

nvm alias default 18.17.0

Method 2: Using the NodeSource PPA Repository

If you only need one specific Node.js version and don’t need to change it often, the PPA (Personal Package Archive) from NodeSource is a simple and effective option.

Step 1: Add the NodeSource PPA

For example, if you want to install Node.js version 20.x:

# Ensure necessary packages are installed
sudo apt-get update
sudo apt-get install -y ca-certificates curl gnupg

# Add NodeSource's GPG key to authenticate packages
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg

# Add the Node.js 20.x repository to the system
NODE_MAJOR=20
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list

Step 2: Install Node.js

Now you just need to update your package list again and install as usual:

sudo apt-get update
sudo apt-get install -y nodejs

This method automatically installs both `node` and `npm`. However, it has a major drawback: upgrading or switching Node.js versions is quite complicated compared to using NVM.

Method 3: From Ubuntu’s Default Repository (Not Recommended)

This is the simplest method, but it is not recommended for a serious development environment. The reason is that the Node.js version in Ubuntu’s default repositories is often very old. For example, while the community has moved on to Node.js 20.x, the default repository might still be offering version 16.x.

sudo apt update
sudo apt install nodejs npm

You should only use this method if you need a “quick-fix” version of Node.js for a simple task and don’t care about the specific version.

Configuration and Optimization

After installation, check the versions again to confirm everything is ready:

node -v
npm -v

When installing with the PPA or the default repository, you will need `sudo` permissions to install global packages (e.g., `npm install -g pm2`). This is not only inconvenient but also poses a potential security risk. To fix this, you should reconfigure the global directory for npm.

Step 1: Create a directory for global packages in your home directory

mkdir ~/.npm-global

Step 2: Configure npm to use this new directory

npm config set prefix '~/.npm-global'

Step 3: Add the directory to the PATH environment variable

Open the `~/.profile` file (or `~/.bashrc`) and add the following line to the end of the file:

export PATH=~/.npm-global/bin:$PATH

Then, run the command `source ~/.profile` to update the PATH for the current session. From now on, any package you install with the `-g` flag will be located in this directory and can be executed from anywhere without needing `sudo`.

Testing and Monitoring the Application

The best way to test is to create a simple Node.js web server.

Step 1: Create the server.js file

Create a file named `server.js` with the following content. This is a minimal web server that listens on port 3000 and returns the string “Hello ITfromZERO!”.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello ITfromZERO!\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Step 2: Run the server

In the terminal, run the command: `node server.js`. You will see the message `Server running at http://127.0.0.1:3000/`.

Step 3: Check the result

Open another terminal and use `curl` to send a request:

curl http://127.0.0.1:3000

If you receive `Hello ITfromZERO!`, congratulations, your Node.js installation is working perfectly!

Monitoring the Application with PM2

When you close the terminal, the `node server.js` application will also stop. For a real deployment, you need a process manager to keep the application running. PM2 is the most popular and powerful choice in the Node.js ecosystem.

Install PM2 (globally):

npm install -g pm2

Run your application with PM2:

pm2 start server.js

The biggest advantage of PM2 is its ability to automatically restart the application if it crashes, ensuring high uptime. It can also start with the system, allowing your application to run automatically whenever the server reboots.

A few useful PM2 commands:

  • `pm2 list`: Lists all applications currently managed by PM2.
  • `pm2 stop server`: Stops the application (replace `server` with the name or id from `pm2 list`).
  • `pm2 restart server`: Restarts the application.
  • `pm2 logs`: View real-time logs of all applications.
  • `pm2 monit`: Opens a dashboard to monitor the CPU and RAM of applications.

Now you have a “standard” toolkit for working with Node.js on Ubuntu: NVM for flexibly switching versions and PM2 to keep your applications running 24/7. Your environment is now ready for any project!

Share: