Node.js

Join filesystem path segments portably

Use node:path join for filesystem path segments instead of manually inserting slash characters. It applies the platform’s path rules and normalizes ordinary separators.

Worked example

Node.js example · save as example.mjs and run node example.mjs

import {join, basename, extname} from "node:path";
const path = join("reports", "daily", "summary.json");
console.log(basename(path));
console.log(extname(path));

How it works

Join expresses that the strings are path segments rather than a URL. Basename retrieves the final filename, and extname retrieves its extension. The displayed separator in the complete path can differ between Windows and POSIX platforms.

Limits and mistakes

Joining is not a security check. A user-supplied parent traversal segment can escape an intended subdirectory after normalization. URL paths also follow different rules, so use the URL API when constructing web addresses.

Check the result

Expect summary.json and .json. Test the complete joined path on each supported operating system, and keep path-containment validation separate from path formatting.

Sources

Reference documentation for the behavior used in this guide: