What does the node:path module provide, and why should you always use it instead of manually concatenating file path strings?
Short answer
The path module provides platform-aware utilities -- join(), resolve(), dirname(), extname() -- that correctly handle the difference between path separators on different OSes, whereas manual string concatenation with a hardcoded '/' would break on Windows.
Advertisement
AModel answer
The path module provides platform-aware utilities -- join(), resolve(), dirname(), extname() -- that correctly handle the difference between path separators on different OSes, whereas manual string concatenation with a hardcoded '/' would break on Windows.
const filePath = path.join(__dirname, 'data', 'users.json');
console.log(path.extname(filePath));Real-world example
A CLI tool that manually concatenated paths worked on macOS but broke on Windows until every path operation was replaced with path.join(), which uses the correct separator per OS.
Likely follow-ups
- What's the difference between path.join() and path.resolve() regarding relative versus absolute output?
- How does path.normalize() clean up redundant segments like '../'?
Related topics