CodingNic

Core Node.js Modules

The path Module: Building File Paths Correctly

Core Node.js Modules 10 min read

The path Module: Building File Paths Correctly

Objectives

By the end of this lesson, you should be able to:

  • Extract parts of a file path with path.dirname, basename, and extname
  • Build paths correctly with path.join and path.resolve
  • Explain why manually concatenating path strings with / is unreliable

💡 Why this matters: Windows uses \ as a path separator, macOS and Linux use /. Building paths by hand with string concatenation breaks on whichever operating system you didn’t test on. The path module handles this correctly, always.

⚠️ A note on verification: every snippet and output in this lesson was actually run with Node.js.

Extracting Parts of a Path

javascript
const path = require('path');

const filePath = '/home/erin/projects/app.js';

console.log(path.dirname(filePath));
console.log(path.basename(filePath));
console.log(path.basename(filePath, '.js'));
console.log(path.extname(filePath));
text
/home/erin/projects
app.js
app
.js

dirname returns everything except the final segment (the containing directory), basename returns just the final segment (the file name), optionally with an extension stripped off if passed as a second argument, and extname returns just the extension.

Building Paths with path.join

javascript
const path = require('path');

const fullPath = path.join('projects', 'my-app', 'src', 'index.js');
console.log(fullPath);

const withDots = path.join('projects', '..', 'other-project', './src');
console.log(withDots);
text
projects/my-app/src/index.js
other-project/src

path.join combines segments using the correct separator for the current operating system, and normalizes the result, resolving .. (parent directory) and . (current directory) segments along the way. This is always safer than 'projects' + '/' + 'my-app', which hardcodes a separator that isn’t correct on every platform.

path.resolve and Absolute Paths

javascript
const path = require('path');

console.log(path.resolve('src', 'index.js'));
console.log(path.resolve('/absolute', 'path.js'));
console.log(path.isAbsolute('/absolute/path.js'));
console.log(path.isAbsolute('relative/path.js'));
text
/tmp/node104/src/index.js
/absolute/path.js
true
false

path.resolve builds an absolute path, if given only relative segments, it resolves them against the current working directory (here, /tmp/node104), if any segment is already absolute, everything before it is discarded and resolution starts fresh from there. path.isAbsolute checks whether a path is already absolute.

path.parse: Every Part at Once

javascript
const path = require('path');

const parsed = path.parse('/home/erin/projects/app.js');
console.log(parsed);
text
{
  root: '/',
  dir: '/home/erin/projects',
  base: 'app.js',
  ext: '.js',
  name: 'app'
}

path.parse returns every part of a path in a single object, root, dir, base (file name with extension), ext, and name (file name without extension), useful when several parts of a path are needed at once instead of calling dirname/basename/extname separately.

Try It

  1. Given the path '/var/www/site/index.html', use path.dirname, path.basename, and path.extname to extract each part separately.
  2. Use path.join to build a path from the segments 'data', '2024', 'reports', 'summary.csv', and print the result.
  3. Use path.resolve with a single relative argument and confirm the result is an absolute path starting from the current working directory.
  4. Use path.parse on any path of your choice and print the resulting object, confirming every field matches what dirname/basename/extname would have given separately.

Recap

  • path.dirname/basename/extname extract individual parts of a path, path.parse returns all of them at once.
  • path.join combines segments with the correct separator and normalizes ./.., always safer than manual string concatenation.
  • path.resolve builds an absolute path, resolving relative segments against the current working directory.

Next lesson: os and process, information about the machine and the running program itself.