Node.js › Path & OS Modules

What does path.parse() and path.format() do, and how are they useful for decomposing and reconstructing file paths?

Beginner

Answer

path.parse() breaks a path string down into an object with its component parts: root, dir, base, ext, and name (the filename without its extension) -- useful for extracting or modifying just one part of a path, like changing a file's extension while keeping everything else the same; path.format() does the reverse, building a path string back up from such an object.
const path = require('node:path');

const parsed = path.parse('/home/user/document.txt');
// { root: '/', dir: '/home/user', base: 'document.txt', ext: '.txt', name: 'document' }

const newPath = path.format({ ...parsed, base: undefined, ext: '.pdf' });
// '/home/user/document.pdf'
Real-world example A file-conversion utility uses path.parse() to extract a file's name and directory, then path.format() to construct a new path with a different extension (like converting document.txt to document.pdf), rather than manually manipulating the path string with substring or regex operations, which would be more error-prone.

Common follow-ups: Why does path.format() require you to omit the 'base' property if you want the 'ext' and 'name' properties to actually take effect?;How would you use path.parse() to write a utility that batch-renames a directory of files with a new extension?