The built-in path module builds and manipulates file paths correctly across operating systems. Manually concatenating path strings with / breaks on Windows (which uses \) and mishandles edge cases — path handles all of it reliably.
The built-in path module builds and manipulates file paths correctly across operating systems. Manually concatenating path strings with / breaks on Windows (which uses \) and mishandles edge cases — path handles all of it reliably.
// ❌ fragile, OS-dependent, error-prone
const filePath = baseDir + "/" + "sub" + "/" + fileName;
// breaks on Windows (\), doubles slashes if baseDir ends in /, etc.
import path from "path";
// ✅ uses the correct separator for the OS, normalizes slashes
const filePath = path.join(baseDir, "sub", fileName);
// Linux/Mac: baseDir/sub/file.txt Windows: baseDir\sub\file.txt
path.join inserts the right separator, collapses duplicate/trailing slashes, and resolves ../. segments.
path.resolve("src", "app.js"); // → ABSOLUTE path from the cwd
path.basename("/a/b/file.txt"); // "file.txt"
path.dirname("/a/b/file.txt"); // "/a/b"
path.extname("file.txt"); // ".txt"
path.parse("/a/b/file.txt"); // { dir, base, name, ext }
path.sep; // "/" or "\" depending on OS
// CommonJS — built-in globals
const configPath = path.join(__dirname, "config.json");
// ES Modules — __dirname doesn't exist; derive it from import.meta.url
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
Building paths relative to the current file (with __dirname, or its ESM equivalent) is the safe way to reference files — independent of where the process was started.
path.join → just joins segments (relative stays relative)
path.resolve → produces an ABSOLUTE path (resolves from cwd / right-to-left)
Using path instead of string concatenation makes file-handling code cross-platform and robust — a frequent source of bugs when code written on Mac/Linux breaks on Windows, or when concatenation produces malformed paths.
It's a small habit with outsized reliability benefits, and knowing join vs resolve, plus how to get __dirname in ESM, covers the everyday path needs in any Node project that touches the file system.