Beginner Node.js Interview QuestionsBeginnerConcept
Node.js · Question 24
What is the Node.js path module?
Direct answer
The path module joins, resolves, and normalizes file paths in an OS-aware way — use path.join and path.resolve instead of string concatenation to avoid broken paths on Windows vs POSIX.
Hardcoding foo/bar/baz breaks on Windows backslashes. path.join uses the correct separator for the current platform.
| Method | Use |
|---|---|
| path.join(...parts) | Safe concatenation — ignores extra slashes |
| path.resolve(...parts) | Absolute path from cwd + segments |
| path.basename(p) | File name — config.json |
| path.dirname(p) | Parent directory |
| path.extname(p) | Extension — .json |
| path.parse(p) | Object with root, dir, base, ext, name |
- Security — path.join upload dir + user input can escape via .. — validate with path.resolve and prefix check (Q66).
- posix vs win32 — path.posix.join for URLs; path.win32 on Windows-specific tools.
path-examples.mjs
import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const dataFile = path.join(__dirname, "data", "interviews", "nodejs");
const absolute = path.resolve("./config", "app.json");
console.log(path.basename(dataFile)); // nodejs
console.log(path.extname(absolute)); // .json