Node.js ยท Chapter 7 of 43

The path Module

The built-in `path` module provides utilities for working with file and directory paths in a way that works across operating systems (Windows uses backslashes, Unix uses forward slashes).

Using `path` instead of manually concatenating strings avoids cross-platform bugs.

Common methods

`path.join()` combines path segments safely, `path.basename()` gets the filename, and `path.extname()` gets the file extension.

Resolving paths

`path.resolve()` turns relative paths into absolute ones based on the current working directory.

Example 1 (javascript)
const path = require('path');
console.log(path.join('folder', 'file.txt'));
console.log(path.extname('file.txt'));
Output
folder/file.txt
.txt

join() safely combines segments; extname() extracts the extension.

Example 2 (javascript)
console.log(path.basename('/users/ada/app.js'));
console.log(path.resolve('app.js'));
Output
app.js
/current/working/dir/app.js

basename() returns just the file name; resolve() returns an absolute path.

Key points

  • path module handles file paths cross-platform.
  • path.join() safely combines path segments.
  • path.basename() and path.extname() extract parts of a path.
  • path.resolve() returns an absolute path.
๐Ÿ’ก Note: Always prefer path.join() over manual string concatenation with '/' or '\\'.

๐Ÿ“ Quick Quiz

1. Which method safely joins path segments?

2. Which method gets the file extension?

3. What does path.resolve() return?