path
The path module provides utilities to work with filesystem paths in a consistent way across platforms.
API Surface
Core Methods
path.join(...segments)— concatenate path segments, normalizing separators.path.resolve(...segments)— resolve into an absolute path.path.normalize(p)— fix..,.and redundant separators.path.isAbsolute(p)— check if absolute.
Name utilities
path.basename(p, [ext])— last part of path (file name).path.dirname(p)— directory portion.path.extname(p)— extension (with leading dot).
Object conversion
path.parse(p)— split into{ root, dir, base, name, ext }.path.format(obj)— inverse ofparse.
Other
path.relative(from, to)— relative path from one to another.path.sep— path separator (/on POSIX,\\on Windows).path.delimiter— PATH env separator (:on POSIX,;on Windows).
Examples (English only)
const path = require("path");
// Join & normalize
console.log(path.join("a", "b", "c.txt")); // a/b/c.txt
// Absolute resolution
console.log(path.resolve("a/b", "../c.txt"));
// Dirname, basename, extname
console.log(path.dirname("/tmp/file.txt")); // /tmp
console.log(path.basename("/tmp/file.txt")); // file.txt
console.log(path.extname("/tmp/file.txt")); // .txt
// Parse & format
const obj = path.parse("/tmp/demo.js");
console.log(obj);
console.log(path.format(obj));
// Relative
console.log(path.relative("/data/orig", "/data/orig/sub/file"));
// Separators
console.log("sep:", path.sep);
console.log("delimiter:", path.delimiter);
Notes
- Use
path.joinwhen concatenating user-supplied or dynamic segments. - Use
path.resolvewhen you need an absolute path relative to CWD. - Extensions include the dot (
.txt). Usebasename(p, ".txt")to strip it. path.sepandpath.delimiterdiffer across operating systems; avoid hardcoding/or:.