Node.js › Path & OS Modules
What does path.parse() and path.format() do, and how are they useful for decomposing and reconstructing file paths?
BeginnerAnswer
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.