This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Node.js path Module Cheatsheet

A quick reference guide for the Node.js path module: path resolution, joining segments, extracting directory names, basenames, extensions, and normalizing paths.

· Published

The path module provides utilities for handling and transforming file and directory paths across POSIX and Windows operating systems.

Joining & Resolving Paths

const path = require('path');

// path.join: Concatenates segments using platform separator
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// => '/foo/bar/baz/asdf'

// path.resolve: Resolves absolute path from right to left
path.resolve('src', 'index.js');
// => '/current/working/dir/src/index.js'

path.resolve('/etc', 'passwd', '..', 'var');
// => '/var'

Inspecting Path Segments

const filePath = '/var/www/site/index.html';

path.dirname(filePath);   // => '/var/www/site'
path.basename(filePath);  // => 'index.html'
path.basename(filePath, '.html'); // => 'index' (strips extension)
path.extname(filePath);   // => '.html'

Parsing & Formatting

// Deconstruct path into structured object
const obj = path.parse('/home/user/notes.md');
/*
{
  root: '/',
  dir: '/home/user',
  base: 'notes.md',
  ext: '.md',
  name: 'notes'
}
*/

// Reconstruct path string from object
path.format(obj); // => '/home/user/notes.md'

Normalization & Relative Paths

// Normalize redundant slashes and dots
path.normalize('/foo/bar//baz/asdf/quux/..');
// => '/foo/bar/baz/asdf'

// Compute relative path from fromPath to toPath
path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
// => '../../impl/bbb'

References

Related topics