path module
The path module is a core Node.js module that provides utilities for manipulating file paths. It solves the problem of cross-platform path compatibility—paths on Windows use backslashes (\\) while Unix-like systems use forward slashes (/). This module lets you write path-agnostic code that works everywhere.
Syntax
const path = require('path'); // CommonJS
import path from 'path'; // ESM
Methods
path.resolve([…paths])
Resolves a sequence of path segments into an absolute path.
| Parameter | Type | Default | Description |
|---|---|---|---|
...paths | string | — | Path segments to resolve |
Returns: string — An absolute path
path.join([…paths])
Joins path segments together using the platform-specific separator.
| Parameter | Type | Default | Description |
|---|---|---|---|
...paths | string | — | Path segments to join |
Returns: string — A joined path
path.basename(path[, ext])
Returns the last portion of a path.
| Parameter | Type | Default | Description |
|---|---|---|---|
path | string | — | The path to evaluate |
ext | string | '' | Optional file extension to remove |
Returns: string — The filename
path.dirname(path)
Returns the directory name of a path.
| Parameter | Type | Default | Description |
|---|---|---|---|
path | string | — | The path to evaluate |
Returns: string — The directory path
path.extname(path)
Returns the extension of the path.
| Parameter | Type | Default | Description |
|---|---|---|---|
path | string | — | The path to evaluate |
Returns: string — The extension including the dot
path.parse(path)
Returns an object with the path’s components.
| Parameter | Type | Default | Description |
|---|---|---|---|
path | string | — | The path to parse |
Returns: Object — { root, dir, base, ext, name }
path.format(pathObject)
Returns a path string from an object (opposite of parse).
| Parameter | Type | Default | Description |
|---|---|---|---|
pathObject | Object | — | Object with path components |
Returns: string — The formatted path
path.isAbsolute(path)
Determines if a path is absolute.
| Parameter | Type | Default | Description |
|---|---|---|---|
path | string | — | The path to check |
Returns: boolean — True if absolute
path.relative(from, to)
Returns the relative path from one to another.
| Parameter | Type | Default | Description |
|---|---|---|---|
from | string | — | Source path |
to | string | — | Target path |
Returns: string — The relative path
path.normalize(path)
Normalizes a path, resolving .. and . segments.
| Parameter | Type | Default | Description |
|---|---|---|---|
path | string | — | The path to normalize |
Returns: string — The normalized path
Examples
Basic path manipulation
const path = require('path');
console.log(__filename);
// /Users/ludwig/project/src/app.js
console.log(__dirname);
// /Users/ludwig/project/src
// Get the filename
console.log(path.basename(__filename));
// app.js
// Get the extension
console.log(path.extname(__filename));
// .js
// Get the directory
console.log(path.dirname(__filename));
// /Users/ludwig/project/src
Building cross-platform paths
const path = require('path');
// Join path segments - automatically uses correct separator
const fullPath = path.join('src', 'components', 'Button.js');
console.log(fullPath);
// 'src/components/Button.js' on Unix
// 'src\\components\\Button.js' on Windows
// Resolve to absolute path
const absolutePath = path.resolve('src', 'app.js');
console.log(absolutePath);
// '/Users/ludwig/project/src/app.js'
Parsing file paths
const path = require('path');
const parsed = path.parse('/home/user/docs/report.pdf');
console.log(parsed);
// {
// root: '/',
// dir: '/home/user/docs',
// base: 'report.pdf',
// ext: '.pdf',
// name: 'report'
// }
// Reconstruct from parsed object
console.log(path.format(parsed));
// '/home/user/docs/report.pdf'
Working with file extensions
const path = require('path');
// Change extension
const file = 'document.txt';
const html = path.basename(file, path.extname(file)) + '.html';
console.log(html);
// 'document.html'
// Check if file has specific extension
function hasExtension(filePath, ext) {
return path.extname(filePath) === ext;
}
console.log(hasExtension('image.png', '.png'));
// true
console.log(hasExtension('image.jpg', '.png'));
// false
Path relative calculations
const path = require('path');
// Get relative path between two directories
const from = '/home/user/project/src';
const to = '/home/user/project/dist/bundle.js';
console.log(path.relative(from, to));
// '../dist/bundle.js'
// Useful for generating import statements
const sourceFile = '/home/user/project/src/utils.js';
const targetDir = '/home/user/project/src/components';
console.log(path.relative(targetDir, sourceFile));
// '../utils.js'
Common Patterns
Resolving project paths
const path = require('path');
// Assuming this file is in src/utils/
const projectRoot = path.resolve(__dirname, '..');
const configPath = path.join(projectRoot, 'config.json');
const srcPath = path.join(projectRoot, 'src');
Safe path joining with user input
const path = require('path');
function safeJoin(base, userInput) {
// Resolve the target path
const targetPath = path.resolve(base, userInput);
// Ensure it's still within the base directory
if (!targetPath.startsWith(base)) {
throw new Error('Path traversal detected');
}
return targetPath;
}
// Usage
const baseDir = '/home/user/uploads';
console.log(safeJoin(baseDir, 'avatar.png'));
// '/home/user/uploads/avatar.png'
console.log(safeJoin(baseDir, '../etc/passwd'));
// Error: Path traversal detected
Cross-platform executable paths
const path = require('path');
// Detect OS and use appropriate extension
const execExt = process.platform === 'win32' ? '.exe' : '';
const binPath = path.join(__dirname, 'bin', 'myapp' + execExt);