Node Essentials
Files & paths
Lesson 3 of 5
What you'll learn
- Read and write files with the promise-based
fsAPI - Build cross-platform paths with
path.join - Model a file store as a name-to-contents map
The filesystem is just a map from paths to contents. Node exposes it through the fs module. Prefer the promise-based version, fs/promises, so reads and writes don't block the event loop:
import { readFile, writeFile } from "node:fs/promises";
await writeFile("greeting.txt", "hello");
const text = await readFile("greeting.txt", "utf8");
console.log(text); // "hello"
Without the "utf8" encoding you'd get a raw Buffer of bytes instead of a string — more on buffers next lesson.
Build paths, never glue them
Hardcoding "folder/file.txt" breaks across operating systems and doubles up slashes. Use path.join: it inserts the correct separator and collapses redundant ones.
import { join } from "node:path";
join("uploads", "2026", "report.txt"); // "uploads/2026/report.txt"
join("uploads/", "/avatar.png"); // "uploads/avatar.png" — no double slash
__dirname for safety
Paths are resolved relative to the working directory, not the file. To reference a file next to your script regardless of where it's run from, join against __dirname (CommonJS) or import.meta.dirname (ESM).
The challenge reimplements path.join and a tiny in-memory file store — the same name-to-contents model the real fs exposes.
Run it. join() cleans up the separators; the store writes, reads, and checks existence by path.
Next: processing data in chunks instead of all at once.
Sign in to save your progress across devices.