Node.js is a powerful, open-source JavaScript runtime built on Chrome’s V8 engine, allowing developers to create scalable and high-performance applications. It is widely used in web development for tasks such as server-side scripting and real-time data handling.
This guide will help you install Node.js on Ubuntu 22.04 using multiple methods. If you’re looking for a quick and easy setup, explore the Node.js app available on our marketplace.
Prerequisites
Ensure your system meets the following requirements:
- Ubuntu 22.04 or a compatible version.
- A user account with sudo privileges.
- Internet access.
Update your system to ensure the latest packages are installed:
sudo apt update
sudo apt upgrade -y
Installing Node.js
Method 1: Using Ubuntu’s default repositories
This is the simplest method, suitable for basic installations.
Step 1: Install Node.js
sudo apt install -y nodejs
sudo apt install -y npm
Step 2: Verify the installation
node -v
npm -v
This method may not install the latest version but ensures compatibility and stability.
Method 2: Using the NodeSource PPA
NodeSource maintains PPAs with various Node.js versions, allowing more flexibility in selecting a specific version.
Step 1: Add the NodeSource PPA
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
Replace 18.x
with the desired version, such as 20.x
for a newer release.
Step 2: Install Node.js and npm
sudo apt install -y nodejs
Step 3: Verify the installation
node -v
npm -v
Method 3: Using Node Version Manager (NVM)
NVM is ideal for developers managing multiple Node.js versions.
Step 1: Install NVM
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
source ~/.bashrc
Step 2: Install Node.js
nvm install --lts
Step 3: Verify the installation
node -v
npm -v
Step 4: Manage versions
- List installed versions:
nvm ls
- Switch versions:
nvm use <version>
- Set a default version:
nvm alias default <version>
Deploying a Node.js application
After installation, test your Node.js environment by deploying a sample application.
Step 1: Create a project directory
mkdir my-node-app && cd my-node-app
Step 2: Initialize the project
npm init -y
Step 3: Create an application file
nano index.js
Add the following code:
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, Node.js!');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Step 4: Run the application
node index.js
Step 5: Access the app at http://127.0.0.1:3000/
in your browser.