How to work with file paths using the path module
· Category: Node.js
Short answer
The path module provides utilities for joining, resolving, normalizing, and parsing file paths in a cross-platform manner.
Steps
- Import the module:
const path = require('path');. - Join paths safely:
path.join('folder', 'file.txt');. - Resolve absolute paths:
path.resolve('folder', 'file.txt');. - Get the directory name:
path.dirname('/tmp/file.txt');. - Get the extension:
path.extname('file.txt');.
Tips
- Always use
path.join()instead of string concatenation to avoid issues with forward versus backward slashes. path.resolve()processes paths from right to left and prepends the current working directory if the result is not absolute.
Common issues
- Hardcoding slashes like
/or\breaks cross-platform compatibility. __dirnamegives the directory of the current module, whileprocess.cwd()gives the working directory where Node was launched.