All academies

Path Module

join, resolve, basename, extname, and cross-platform paths.

12 minLevel 9 of 20

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.

Concatenation vs path.join
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.

join and resolve, side by side
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 segment
  • path.extname(p) — the extension including the dot: ".pdf"
  • path.parse(p) — all of the above at once, as an object with root, dir, base, name, ext

path.format() is the inverse of parse — it builds a path string back from such an object.

Dissecting a path
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 after cd
  • path.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.

relative, normalize, isAbsolute
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"));  // false

Cross-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.join or path.resolve, never string concatenation
  • Anchor files that ship with your app on __dirname, not process.cwd()
  • Compare extensions case-insensitively (.JPG vs .jpg)
  • For URLs, always use forward slashes — path.posix.join helps when generating them
Platform constants and the classic pattern
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 questions

Question 1 of 5

Score: 0

Multiple choice

What is the key difference between path.join and path.resolve?