How To Install Node Js On Ubuntu

Node js is an open-sourced javascript cross-platform that is built on a chrome V8 javascript engine and runs on Windows, macOS and Linux systems that use x64, IA-32, ARM, or MIPS processors. To take benefit of javascript on both backend and frontend so you can run javascript on your machine as a standalone application.

Step 1. Install Node js on Ubuntu 16.04 and 18.04

In this tutorial, we will learn how to install Node js & npm and cover installation of both:

  1. Distro stable version
  2. PPA for Ubuntu.

Note: In this tutorial, The current LTS version of node js is 10.15.3. If you want to install the latest version of node js use PPA

Let's get started

Method 1. Install distro stable version on ubuntu

Before we install nodejs. we need to refresh our apt to update the package lists. Enter the following command to update.

sudo apt-get update

Next, Enter the following command to install the node js

sudo apt-get install nodejs

Next install NPM. Enter the following command to install npm

sudo apt-get install npm

Method 2. Install nodejs from PPA on Ubuntu

To install from PPA First, you need to add PPA to your apt package manager. But before that make sure curl and software-common-properties is installed on your system.

If not run the following command to install.

sudo apt install curl
sudo apt-get install software-properties-common

Once you are done, Enter the following command to add the PPA

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

Once you add the PPA, Enter the following command to install nodejs

sudo apt-get install -y nodejs

Step 2. Check Nodejs and NPM version.

To make sure nodejs and npm are installed on your system. Enter the following command to check the node js and npm version 

node -v
npm -v

Step 3. Create a dummy web server

In this section, we will create a dummy webserver to test the nodejs.

Create a file and paste the following code

#/var/www/html/index.js

const http = require('http');
const port = 8020;

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

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

Save it and run node index.js and open https://localhost:8020 you will see the output `Hello world`.