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.
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
# https://nodejs.org → install LTS
node --version # v20.x or newer
npm --versionUse nvm (Node Version Manager) if you work on multiple projects with different Node versions.
3. Run JavaScript
// hello.js
console.log("Hello from Node!");
console.log("Node version:", process.version);node hello.js
node -e "console.log(2 + 2)" # one-liner
node # interactive REPL4. 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
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
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
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 code4. http — Built-in Server
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
mkdir my-app && cd my-app
npm init -y # creates package.json
npm install chalk # adds to dependencies
npm install --save-dev nodemon # devDependencies2. package.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" }
}npm run dev # runs the "dev" script
npm start # 'start' is a special shortcut3. Semver
| Range | Meaning |
|---|---|
| ^1.2.3 | Compatible: >=1.2.3, <2.0.0 (most common default) |
| ~1.2.3 | Patch: >=1.2.3, <1.3.0 |
| 1.2.3 | Exact |
| >=1.2.3 | Anything 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
npm install expressimport 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
// 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
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
// 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.
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