path Module Splits And Joins Segments

Compose and decompose filesystem paths with join, resolve, basename, extname, and dirname so path logic never relies on string concatenation.

JavascriptCli Tooling

Code

javascriptsnippet
17 lines
import { join, resolve, basename, extname, dirname, sep, isAbsolute } from 'node:path';

const full = join('assets', 'icons', 'logo.svg');
console.log('joined:', full);
console.log('basename:', basename(full));
console.log('without extension:', basename(full, extname(full)));
console.log('extension:', extname(full));
console.log('dirname:', dirname(full));

// resolve anchors a relative path to the current working directory
const absolute = resolve(full);
console.log('resolve makes it absolute:', isAbsolute(absolute));
console.log('ends with joined path:', absolute.endsWith(full));

// join normalizes redundant separators and parent segments
console.log('normalized:', join('assets', '.', 'icons', '..', 'icons', 'logo.svg'));
console.log('separator:', JSON.stringify(sep));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

joined: assets\icons\logo.svg
basename: logo.svg
without extension: logo
extension: .svg
dirname: assets\icons
resolve makes it absolute: true
ends with joined path: true
normalized: assets\icons\logo.svg
separator: "\\"

How it works

The only import source is node:path, a Node.js built-in, exposing join, resolve, basename, extname, dirname.

The file’s state is a handful of top-level bindings: full, absolute.

Points of care

  • node:path is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Using it

The run emits 9 labeled sections — joined:, basename:, without extension:, extension:, dirname:, resolve makes it absolute:, ends with joined path:, normalized:, separator: — one per step.

Key statements

const full = join('assets', 'icons', 'logo.svg');
const absolute = resolve(full);

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The imports resolve to Node.js core modules, which the runtime provides.