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

  1. Import the module: const path = require('path');.
  2. Join paths safely: path.join('folder', 'file.txt');.
  3. Resolve absolute paths: path.resolve('folder', 'file.txt');.
  4. Get the directory name: path.dirname('/tmp/file.txt');.
  5. 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.
  • __dirname gives the directory of the current module, while process.cwd() gives the working directory where Node was launched.