Web Development · Module 10 · Lesson 11 min read

Node.js Basics

JavaScript on the server

Node.js runs JavaScript outside the browser, using Chrome's V8 engine. With it you can build APIs, command-line tools and real-time servers, all in the same language as your front end.

What's different from the browser

BrowserNode.js
window, document, the DOMno DOM
limited file accessfull file system (fs)
fetch, localStoragefetch, plus http, fs, path, process…
runs your user's coderuns your server code

Non-blocking I/O

Node handles many connections on a single thread by not waiting: while one request waits for the database, it serves others. That makes it great for I/O-heavy apps like APIs and chat. CPU-heavy work (video encoding, big maths) blocks the thread, so move it to worker threads or another service.

Built-in modules

JavaScript
import fs from "node:fs/promises";
import path from "node:path";

const text = await fs.readFile(path.join("data", "notes.txt"), "utf8");

Running code

  • node app.js runs a file.
  • node --watch app.js restarts automatically on changes (Node 18+).
  • process.env.PORT reads environment variables.

💡 Install the LTS (long-term support) version of Node.js from nodejs.org.

Example

JavaScript
// server.js — a tiny HTTP server with only built-in modules
import http from "node:http";

const server = http.createServer((req, res) => {
  if (req.url === "/api/hello") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ message: "Hello from Node!" }));
    return;
  }
  res.writeHead(404, { "Content-Type": "text/plain" });
  res.end("Not found");
});

const PORT = process.env.PORT ?? 3000;
server.listen(PORT, () => console.log(`Running on http://localhost:${PORT}`));
// Run: node server.js   (package.json needs "type": "module")
// 💻 Run on a computer with Node.js