π’
EPISODE 02
fs Β· path Β· os Β· http
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.
fspathoshttpBuilt-in
Duration
β± About 1.5 hours
Level
π Beginner+
Prerequisite
π― node-01
OUTCOME
Read/write files and serve a basic HTTP response β no npm needed
What you'll learn
- 1Read and write files with fs.promises
- 2Build cross-platform paths with path.join
- 3Inspect environment with os and process.env
- 4Start a basic HTTP server with the 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 code4. 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).
Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub β