← Back to the Build Your Homepage series
🟢
EPISODE 01
Why Node? · install · REPL · running scripts · fs · path · os · http · package.json · npm install · scripts · semver · routing · middleware · JSON parser · static files

Node.js Basics · Node.js Built-in Modules · npm & Packages · Express.js

Run JavaScript outside the browser. Install Node, use the REPL, run scripts, and understand the runtime model and event loop at a high level. Use Node's built-in modules: read and write files with fs, build paths safely with path, inspect the OS, and serve HTTP with the built-in http module. Use npm to manage dependencies, run scripts, and publish your own packages. Understand semver and lockfiles. Build real HTTP servers fast with Express. Learn routing, middleware composition, JSON body parsing, and serving static files.

Node.jsREPLevent loopruntimefspathoshttpBuilt-innpmpackage.jsonsemverscriptsExpressroutingmiddlewareREST
Duration
⏱ About 1 hour + About 1.5 hours + About 1.5 hours + About 2 hours
Level
📊 Beginner
Prerequisite
🎯 JavaScript basics
OUTCOME
Run JavaScript files from your terminal with Node / Read/write files and serve a basic HTTP response — no npm needed / Create a Node project that pulls in npm packages and runs custom scripts / An Express server with multiple routes, middleware, and static assets

What you'll learn

  • 1Install Node (LTS) and verify versions
  • 2Run scripts with node file.js
  • 3Use the REPL for quick experiments
  • 4Understand the event loop in plain English
  • 5Read and write files with fs.promises
  • 6Build cross-platform paths with path.join
  • 7Inspect environment with os and process.env
  • 8Start a basic HTTP server with the http module
  • 9Initialize a package.json
  • 10Install, update, and remove dependencies
  • 11Define and run npm scripts
  • 12Read semver ranges (^, ~, exact)
  • 13Set up an Express app and route handlers
  • 14Use built-in JSON and static middleware
  • 15Write custom middleware (logging, auth check)
  • 16Handle errors centrally

Node.js Basics

Run JavaScript outside the browser. Install Node, use the REPL, run scripts, and understand the runtime model and event loop at a high level.

1. What is Node.js?

  • A runtime that executes JavaScript outside the browser (built on V8)
  • Single-threaded event loop with non-blocking I/O
  • Used for servers, CLI tools, build tooling, and more

2. Install

bash
# https://nodejs.org → install LTS
node --version    # v20.x or newer
npm --version
💡

Use nvm (Node Version Manager) if you work on multiple projects with different Node versions.

3. Run JavaScript

javascript
// hello.js
console.log("Hello from Node!");
console.log("Node version:", process.version);
bash
node hello.js
node -e "console.log(2 + 2)"   # one-liner
node                            # interactive REPL

4. The Event Loop (Simple Mental Model)

  • JavaScript runs on a single main thread
  • Async operations (I/O, timers) are handed off to the platform
  • When they finish, callbacks are queued and run on the main thread
  • So your code never blocks waiting — but heavy CPU work still does

Node.js Built-in Modules

Use Node's built-in modules: read and write files with fs, build paths safely with path, inspect the OS, and serve HTTP with the built-in http module.

1. fs — File System

javascript
import fs from "node:fs/promises";

await fs.writeFile("notes.txt", "Hello, Node!");
const text = await fs.readFile("notes.txt", "utf8");
console.log(text);

const files = await fs.readdir(".");
console.log(files);
💡

Prefer the promise API (node:fs/promises) over callbacks — cleaner with async/await.

2. path — Cross-platform Paths

javascript
import path from "node:path";

const p = path.join("data", "users", "alice.json");
// Windows: data\users\alice.json
// macOS/Linux: data/users/alice.json

path.extname("photo.jpg");  // ".jpg"
path.basename(p);            // "alice.json"

3. os and process

javascript
import os from "node:os";

os.platform();   // 'darwin' | 'linux' | 'win32'
os.cpus().length;
os.totalmem();

process.env.PORT;         // environment variable
process.argv;             // command-line args
process.exit(1);          // exit with error code

4. http — Built-in Server

javascript
import http from "node:http";

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end(`Hello from Node! ${req.method} ${req.url}\n`);
});

server.listen(3000, () => console.log("http://localhost:3000"));

Powerful but verbose. Real projects use Express or another framework (next lesson).

npm & Packages

Use npm to manage dependencies, run scripts, and publish your own packages. Understand semver and lockfiles.

1. Start a Project

bash
mkdir my-app && cd my-app
npm init -y          # creates package.json
npm install chalk    # adds to dependencies
npm install --save-dev nodemon   # devDependencies

2. package.json

json
{
  "name": "my-app",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "start": "node index.js",
    "dev":   "nodemon index.js",
    "test":  "node --test"
  },
  "dependencies": { "chalk": "^5.3.0" },
  "devDependencies": { "nodemon": "^3.0.0" }
}
bash
npm run dev          # runs the "dev" script
npm start            # 'start' is a special shortcut

3. Semver

RangeMeaning
^1.2.3Compatible: >=1.2.3, <2.0.0 (most common default)
~1.2.3Patch: >=1.2.3, <1.3.0
1.2.3Exact
>=1.2.3Anything newer
*Any version (avoid)

4. The Lockfile

  • npm install also writes package-lock.json with the exact resolved versions
  • Commit the lockfile — it makes installs reproducible across machines
  • Use npm ci in CI for fast, exact installs from the lockfile

Express.js

Build real HTTP servers fast with Express. Learn routing, middleware composition, JSON body parsing, and serving static files.

1. Hello, Express

bash
npm install express
javascript
import express from "express";
const app = express();

app.get("/", (req, res) => {
  res.send("Hello from Express!");
});

app.get("/api/hello/:name", (req, res) => {
  res.json({ message: `Hello, ${req.params.name}!` });
});

app.listen(3000, () => console.log("http://localhost:3000"));

2. Middleware

javascript
// Built-in: parse JSON bodies
app.use(express.json());

// Built-in: serve files from /public
app.use(express.static("public"));

// Custom: log every request
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

Middleware runs in the order it is registered. Always call next() unless you send a response.

3. Route Methods

javascript
app.post("/users", (req, res) => {
  const user = req.body;       // populated by express.json()
  // ... save to database ...
  res.status(201).json(user);
});

app.put("/users/:id", (req, res) => { /* ... */ });
app.delete("/users/:id", (req, res) => { /* ... */ });

4. Error Handling

javascript
// 404 (no route matched)
app.use((req, res) => {
  res.status(404).json({ error: "Not found" });
});

// Error middleware (4 args!)
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: "Internal server error" });
});
⚠️

Error middleware must have 4 parameters (err, req, res, next) — that signature is how Express recognizes it.

Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub ↗

Comments 0

No comments yet. Be the first.

Only members can comment.

Comments with ads, abuse, personal information or illegal content are hidden or removed. Comments are shown with your nickname. Privacy Policy