20.1 C
New York

How to Install Node.js and npm on Ubuntu 22.04: A Comprehensive Tutorial

Published:

Node.js, a powerful JavaScript runtime built on Chrome’s V8 engine, is designed for building scalable network applications. npm is Node.js’s default package manager and a vast software registry. This guide covers three methods for installing Node.js and npm on Ubuntu 22.04, each catering to different requirements.

Method 1: Installing Node.js and npm from NodeSource

NodeSource provides an enterprise-grade Node support with an APT repository containing multiple Node.js versions.

  1. Install Dependencies:
    Update the package list and install necessary packages:
   sudo apt update
   sudo apt install ca-certificates curl gnupg
  1. Import NodeSource Repository GPG Key:
   sudo mkdir -p /etc/apt/keyrings
   curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
  1. Add NodeSource Repository:
    For Node.js v20.x, create the NodeSource repository file:
   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
   sudo apt update
  1. Install Node.js and npm:
   sudo apt install nodejs

Verify the installation:

   node --version
   npm --version

Install development tools for compiling native addons:

   sudo apt install build-essential

Method 2: Using NVM (Node Version Manager)

NVM allows managing multiple Node.js versions on a single machine.

  1. Install NVM:
    Download and install the nvm script:
   wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

Reopen the terminal or source the nvm script:

   export NVM_DIR="$HOME/.nvm"
   [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
  1. Verify NVM Installation:
   nvm --version
  1. Install Node.js Versions:
    Install the latest Node.js version:
   nvm install node

For LTS or a specific version (e.g., v16.15.0):

   nvm install --lts
   nvm install 16.15.0

Switch between installed versions:

   nvm use 16.15.0

Set the default Node.js version:

   nvm alias default 16.15.0

Method 3: Installing from Ubuntu Repositories

This method installs Node.js and npm from the Ubuntu repository.

  1. Install Node.js and npm:
    Update the package index and install:
   sudo apt update
   sudo apt install nodejs npm

Verify the installation:

   nodejs --version

Conclusion

These three methods provide flexibility in installing Node.js and npm on Ubuntu 22.04, whether you need a specific version, multiple versions, or the simplicity of using the Ubuntu repository. The choice depends on your specific use case and requirements. For additional assistance or questions, feel free to leave a comment.

Related articles

Recent articles