Working with Paths
The path module builds and parses file paths safely.
Syntax
path.join(__dirname, 'files', 'a.txt')File paths look different on Windows (\) and macOS/Linux (/). The built-in path module handles these differences for you.
Useful functions
path.join(...)— join segments with the correct separator.path.resolve(...)— build an absolute path.path.basename(p)— the file name.path.extname(p)— the file extension.
Example
const path = require('path');
const full = path.join('users', 'ada', 'report.pdf');
console.log(full); // users/ada/report.pdf
console.log(path.basename(full)); // report.pdf
console.log(path.extname(full)); // .pdf
console.log(path.dirname(full)); // users/adaWhen to use it
- A web server uses `path.join(__dirname, 'public', req.url)` to safely resolve requested static file paths and prevent directory-traversal attacks.
- A cross-platform build script uses `path.join` instead of string concatenation so it works on both Windows and Unix without path-separator bugs.
- A CLI tool uses `path.extname(file)` to filter only `.csv` files from a directory listing before processing them.
More examples
path.join and path.resolve
Contrasts `path.join` (relative) and `path.resolve` (absolute) for building file paths.
const path = require('path');
console.log(path.join('src', 'utils', 'index.js'));
// 'src/utils/index.js' (uses OS separator)
console.log(path.resolve('src', 'utils', 'index.js'));
// '/absolute/path/to/src/utils/index.js'Dissect a path with path methods
Uses `dirname`, `basename`, `extname`, and `parse` to extract components from a full file path.
const path = require('path');
const file = '/home/user/project/src/server.js';
console.log(path.dirname(file)); // '/home/user/project/src'
console.log(path.basename(file)); // 'server.js'
console.log(path.extname(file)); // '.js'
console.log(path.parse(file));Normalize a messy path
Uses `path.normalize` to clean up redundant separators, `.`, and `..` segments in a path string.
const path = require('path');
const messy = '/home/user/../user/./project//src';
console.log(path.normalize(messy));
// '/home/user/project/src'
Discussion