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, andextname - Build paths correctly with
path.joinandpath.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. Thepathmodule 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
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));
/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
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);
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
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'));
/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
const path = require('path');
const parsed = path.parse('/home/erin/projects/app.js');
console.log(parsed);
{
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
- Given the path
'/var/www/site/index.html', usepath.dirname,path.basename, andpath.extnameto extract each part separately. - Use
path.jointo build a path from the segments'data','2024','reports','summary.csv', and print the result. - Use
path.resolvewith a single relative argument and confirm the result is an absolute path starting from the current working directory. - Use
path.parseon any path of your choice and print the resulting object, confirming every field matches whatdirname/basename/extnamewould have given separately.
Recap
path.dirname/basename/extnameextract individual parts of a path,path.parsereturns all of them at once.path.joincombines segments with the correct separator and normalizes./.., always safer than manual string concatenation.path.resolvebuilds 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.