Path Module
join, resolve, basename, extname, and cross-platform paths.
Why a whole module for paths?
File paths look like plain strings, but they hide platform differences and edge cases. Windows separates with backslashes (C:\\Users\\me), Unix systems with forward slashes (/home/me). Segments like .. and . need normalizing. Trailing slashes, double slashes, drive letters...
Hand-concatenating paths with + produces bugs that only appear on someone else's machine. The path module handles every platform quirk for you — always build paths with it.
const path = require("path");
// Fragile - breaks with missing/extra slashes and on Windows:
const bad = "uploads" + "/" + "//images/" + "photo.png";
console.log("concatenated:", bad);
// Robust - normalizes separators and duplicates:
const good = path.join("uploads", "//images/", "photo.png");
console.log("path.join: ", good);join vs resolve
The two workhorses are easy to confuse:
path.join(...parts)— glues segments together and normalizes the result. The output is relative if the inputs are relative.path.resolve(...parts)— builds an absolute path, working right-to-left until it has one. If no segment is absolute, it prefixes the current working directory.
Think of resolve as answering: *"if I cd into each of these in order, where do I end up?"* An absolute segment resets the result, and .. climbs up.
const path = require("path");
console.log(path.join("a", "b", "c")); // a/b/c (relative)
console.log(path.join("/a", "b", "..", "c")); // /a/c (normalized)
console.log(path.resolve("a", "b")); // <cwd>/a/b (absolute!)
console.log(path.resolve("/x", "y")); // /x/y
console.log(path.resolve("/x", "/z")); // /z - absolute segment resets
console.log("cwd is:", process.cwd());Taking paths apart
Given a path, you often need one piece of it:
path.basename(p)— the last segment:"report.pdf"path.basename(p, ".pdf")— the last segment minus a suffix:"report"path.dirname(p)— everything before the last segmentpath.extname(p)— the extension including the dot:".pdf"path.parse(p)— all of the above at once, as an object withroot,dir,base,name,ext
path.format() is the inverse of parse — it builds a path string back from such an object.
const path = require("path");
const p = "/home/ada/projects/report.pdf";
console.log("basename:", path.basename(p)); // report.pdf
console.log("name only:", path.basename(p, ".pdf")); // report
console.log("dirname: ", path.dirname(p)); // /home/ada/projects
console.log("extname: ", path.extname(p)); // .pdf
console.log(path.parse(p));
// { root: '/', dir: '/home/ada/projects',
// base: 'report.pdf', ext: '.pdf', name: 'report' }Relative paths and normalization
Two more utilities round out the toolkit:
path.relative(from, to)— computes how to get from one path to another: the string you'd type aftercdpath.normalize(p)— collapses..,., and duplicate separators in a messy path string
path.isAbsolute(p) tells you whether a path is anchored at the root — useful when validating user-supplied paths.
const path = require("path");
console.log(path.relative("/app/src", "/app/dist/js"));
// ../dist/js
console.log(path.normalize("/app//src/../lib/./utils.js"));
// /app/lib/utils.js
console.log(path.isAbsolute("/etc/config")); // true
console.log(path.isAbsolute("etc/config")); // falseCross-platform habits
Three constants expose platform details: path.sep (separator: / or \\), path.delimiter (PATH-variable separator: : or ;), and the path.posix / path.win32 namespaces that force one platform's behavior regardless of where you run.
Habits that keep code portable:
- Build every path with
path.joinorpath.resolve, never string concatenation - Anchor files that ship with your app on
__dirname, notprocess.cwd() - Compare extensions case-insensitively (
.JPGvs.jpg) - For URLs, always use forward slashes —
path.posix.joinhelps when generating them
const path = require("path");
console.log("separator:", JSON.stringify(path.sep));
console.log("PATH delimiter:", JSON.stringify(path.delimiter));
// Forcing POSIX behavior (handy for URLs):
console.log(path.posix.join("assets", "img", "logo.svg"));
// The pattern you will type a thousand times:
const dataFile = path.join(__dirname, "data", "users.json");
console.log("app file:", dataFile);Check your understanding
5 questionsQuestion 1 of 5
Score: 0