Introduction

Node.js is a popular runtime environment for executing JavaScript code outside of a web browser. In this guide, we'll walk through the steps to install Node.js on Ubuntu 20.04, configure it, and run a sample app.

Prerequisites

Before proceeding, ensure you have:

  1. An Ubuntu 20.04 server
  2. Terminal or SSH access to your server

Steps to Install Node.js and npm

    1. Update Package Index: Before installing Node.js, update the package index on your Ubuntu server:
sudo apt update
    1. Install Node.js: Use the following command to install Node.js from the default Ubuntu repositories:
sudo apt install nodejs
    1. Install npm: npm is a package manager for Node.js. Install it using the following command:
sudo apt install npm

Run a Sample Node.js App

    1. Create a Directory: Create a directory for your Node.js app:
mkdir myapp
cd myapp
    1. Create a JavaScript File: Create a JavaScript file for your Node.js app. For example, create a file named app.js and 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, World!\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
    1. Run the App: Use the following command to run the Node.js app:
node app.js

Your Node.js app should now be running and accessible at http://127.0.0.1:3000/

Conclusion

Congratulations! You have successfully installed Node.js and npm on your Ubuntu 20.04 server, configured them, and run a sample Node.js app. You can now start developing and running JavaScript applications using Node.js.

Was this answer helpful? 0 Users Found This Useful (0 Votes)