DEV Community

Cover image for NodeJS on Ubuntu: Installation, Setup, and First Steps
Javier Jimenez
Javier Jimenez

Posted on

NodeJS on Ubuntu: Installation, Setup, and First Steps

NodeJs - Logo

I recommend seeing first – installation of Homebrew and asdf on Ubuntu (it’s short, only 5 commands)

📘 Official Documentation


⭐ Popular Frameworks (ordered from lower to higher learning curve)

  • Express — Minimalist and flexible framework for creating APIs and HTTP servers with Node.js.
  • Fastify — Fast and efficient framework focused on high performance and low resource consumption.
  • NestJS — Modular and structured framework inspired by Angular, ideal for scalable applications in Node.js.

🛠️ Installation on Ubuntu

sudo apt update
sudo apt install nodejs npm
Enter fullscreen mode Exit fullscreen mode

For updated versions, NodeSource is recommended:

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
Enter fullscreen mode Exit fullscreen mode

🍺 Installation with Homebrew

brew install node
Enter fullscreen mode Exit fullscreen mode

📦 Standard Package Manager

Node uses npm (included by default) or pnpm/yarn optionally.

Install pnpm (globally):

npm install -g pnpm
Enter fullscreen mode Exit fullscreen mode

🔧 Installation with ASDF

# add plugin
asdf plugin add nodejs https://github.com/asdf-vm/asdf-nodejs.git

# import keys
bash ~/.asdf/plugins/nodejs/bin/import-release-team-keyring

# install a version
asdf install nodejs 20.11.0

# set global or local
asdf global nodejs 20.11.0
# or
asdf local nodejs 20.11.0
Enter fullscreen mode Exit fullscreen mode

📄 Example .tool-versions

nodejs 20.11.0
Enter fullscreen mode Exit fullscreen mode

🔧 Install NVM (Node Version Manager)

Beyond the fact that asdf can be used to unify all version managers into one tool, the truth is that the standard in Node is NVM, so it also seems correct to include the standard to get familiar with it.

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

source ~/.nvm/nvm.sh
Enter fullscreen mode Exit fullscreen mode

Install a version of Node.js with NVM

# Install the latest LTS version
nvm install --lts

# Install a specific version
nvm install 20.11.0

# Use an installed version
nvm use 20.11.0

# Set default version
nvm alias default 20.11.0

# Useful NVM commands list
nvm ls
nvm ls-remote
nvm ls-remote --lts
nvm ls
nvm uninstall 18
Enter fullscreen mode Exit fullscreen mode

📄 Example .nvmrc

20.11.0
Enter fullscreen mode Exit fullscreen mode

📝▶️ Create and run a Node.js file

Create file: touch index.js

Contents of index.js

console.log('Hola Mundo Node');
Enter fullscreen mode Exit fullscreen mode

💻 Run locally:

node index.js
Enter fullscreen mode Exit fullscreen mode

quieres saber mas?


🟩 Basic Example in Node.js

🗂️🌐 Static Files Web Server

What It Does:

  1. Defines the name of the query parameter
  2. Gets the value of the query parameter from the URL
    • url.searchParams.get() is used to access query parameters.
    • and stripTags(input) is used to clean < and > tags into HTML entities.
  3. Renders the variable received in the query parameter inside the <H1> tag

📝 Create file: touch server.js

📦 Contents of server.js

import http from "http";
import { URL } from "url";

// URL sanitization
function stripTags(input) {
  return input.replace(/<[^>]*>/g, "");
}

const server = http.createServer((req, res) => {
  const url = new URL(req.url, `http://localho7000`);
  const username = stripTags(url.searchParams.get("username") || "invitado");

  const html = `
    <!DOCTYPE html>
    <html lang="es">
    <head><meta charset="UTF-8"><title>Hola</title></head>
    <body style="text-align:center">
        <h1>Hola, ${username}</h1>
    </body>
    </html>
  `;

  res.writeHead(200, { "Content-Type": "text/html" });
  res.end(html);
});

server.listen(7000, () => {
  console.log("Server at http://localhost:7000?username=Homero");
});
Enter fullscreen mode Exit fullscreen mode

▶️ Run the project / start the server

node index.js
Enter fullscreen mode Exit fullscreen mode

👉 visit:
http://localhost:8000/?username=javier


⚙️🧩 JSON REST API

What It Does:

  1. Reads data from a data.json file
  2. Exposes 1 endpoint with that data
    • A list of characters at /characters
    • And character data by id /characters/:id

Example file: data.json

[
  {
    "id": 1,
    "age": 39,
    "name": "Homer Tompson",
    "portrait_path": "https://cdn.thesimpsonsapi.com/500/character/1.webp"
  },
  {
    "id": 2,
    "age": 39,
    "name": "Marge Simpson",
    "portrait_path": "https://cdn.thesimpsonsapi.com/500/character/2.webp"
  }
]
Enter fullscreen mode Exit fullscreen mode

📝 Create file: touch api.js

▶️ File contents: api.js

import http from "http";
import fs from "fs";
import url from "url";

function loadCharacters() {
  const json = fs.readFileSync("data.json", "utf8");
  return JSON.parse(json);
}

const server = http.createServer((req, res) => {
  res.setHeader("Content-Type", "application/json");

  const parsedUrl = url.parse(req.url, true);
  const path = parsedUrl.pathname;
  const method = req.method;

  const characters = loadCharacters();

  // GET /characters → full list
  if (method === "GET" && path === "/characters") {
    res.end(JSON.stringify(characters));
    return;
  }

  // GET /characters/:id → find by ID
  const match = path.match(/^\/characters\/(\d+)$/);
  if (method === "GET" && match) {
    const id = parseInt(match[1], 10);
    const found = characters.find((c) => c.id === id);

    if (found) {
      res.end(JSON.stringify(found));
      return;
    }

    res.statusCode = 404;
    res.end(JSON.stringify({ error: "Character not found" }));
    return;
  }

  // Route not found
  res.statusCode = 404;
  res.end(
    JSON.stringify({
      error: "Route not found",
      url_lista: "http://localhost:7001/characters",
      url_personaje: "http://localhost:7001/characters/1"
    })
  );
});

server.listen(7001, () => {
  console.log("Server running at http://localhost:7001/characters");
});
Enter fullscreen mode Exit fullscreen mode

▶️ Run the project / start the server

node api.js
Enter fullscreen mode Exit fullscreen mode

👉 visit:
http://localhost:7001/characters

To test URL sanitization:
http://localhost:7001/characters/1


Installation and configuration on Ubuntu of:

Top comments (0)