Master Node.js Path Module: Get, Join, Resolve, and Parse File Paths
This article provides a comprehensive guide to Node.js's path module, covering how to retrieve directories, filenames, and extensions, combine and resolve paths, normalize and parse paths, format and decompose file paths, compute relative paths, and handle platform-specific differences.
Module Overview
In Node.js, the path module is frequently used but can be confusing due to unclear documentation and platform differences; grouping its interfaces by purpose makes it easier to understand.
1 Get Path / Filename / Extension
Get directory: path.dirname(filepath) Get filename: path.basename(filepath) Get extension:
path.extname(filepath)1.1 Get directory
Example:
var path = require('path');
var filepath = '/tmp/demo/js/test.js';
console.log(path.dirname(filepath)); // /tmp/demo/js1.2 Get filename
path.basename(filepath)returns the last part of the path; it does not verify that the name corresponds to an actual file.
var path = require('path');
console.log(path.basename('/tmp/demo/js/test.js')); // test.js
console.log(path.basename('/tmp/demo/js/test')); // testTo obtain the filename without its extension, pass the extension as a second argument:
console.log(path.basename('/tmp/demo/js/test.js', '.js')); // test1.3 Get extension
Example:
var path = require('path');
var filepath = '/tmp/demo/js/test.js';
console.log(path.extname(filepath)); // .jsRules: extract from the last '.' to the end; if no '.' exists or the first character is '.', return an empty string.
Extract from the last '.' to the end.
If no '.' or the first character is '.', return an empty string.
Official examples:
path.extname('index.html') // '.html'
path.extname('index.coffee.md') // '.md'
path.extname('index.') // '.'
path.extname('index') // ''
path.extname('.index') // ''2 Path Combination
path.join([...paths]) path.resolve([...paths])2.1 path.join
Joins the given paths and normalizes the result.
2.2 path.resolve
Resolves a sequence of paths to an absolute path, similar to executing cd commands in a shell.
Example:
var path = require('path');
// Assuming current working directory is /Users/a/.../node-path
console.log(path.resolve('')); // current working directory
console.log(path.resolve('.')); // current working directory
console.log(path.resolve('/foo/bar', './baz')); // /foo/bar/baz
console.log(path.resolve('/foo/bar', './baz/')); // /foo/bar/baz
console.log(path.resolve('/foo/bar', '/tmp/file/')); // /tmp/file
console.log(path.resolve('www', 'js/upload', '../mod.js')); // /Users/a/.../node-path/www/js/mod.js3 Path Parsing
Interface:
path.parse(path)3.1 path.normalize(filepath)
Normalizes a path by resolving '.' and '..', collapsing duplicate separators, and handling trailing slashes.
If the path is empty, returns '.' (the current directory).
Collapses repeated separators (e.g., '//' becomes '/').
Processes '.' and '..' similarly to shell navigation.
Preserves a trailing '/' if present.
In other words, path.normalize is "What is the shortest path I can take that will take me to the same place as the input".
Example demonstrating various cases:
var path = require('path');
var filepath = '/tmp/demo/js/test.js';
var index = 0;
function compare(desc, callback){
console.log('[Case %d]: %s', ++index, desc);
callback();
console.log('
');
}
compare('Empty path', function(){ console.log(path.normalize('')); });
compare('Trailing slash', function(){ console.log(path.normalize('/tmp/demo/js/upload')); console.log(path.normalize('/tmp/demo/js/upload/')); });
compare('Duplicate separators', function(){ console.log(path.normalize('/tmp/demo//js')); });
compare('Path with ..', function(){ console.log(path.normalize('/tmp/demo/js/upload/..')); });
compare('Relative path', function(){ console.log(path.normalize('./demo/js/upload/')); console.log(path.normalize('demo/js/upload/')); });
compare('Edge cases', function(){ console.log(path.normalize('./..')); console.log(path.normalize('..')); console.log(path.normalize('../')); console.log(path.normalize('/../')); console.log(path.normalize('/..')); });4 File Path Formatting / Parsing
path.format(pathObject)combines root, dir, base, name, and ext into a path string. path.parse(filepath) performs the inverse operation.
Linux and Windows attribute tables (illustrated with images).
4.1 path.format
rootand dir are interchangeable; root does not automatically add a separator, while dir does. Likewise, base can be replaced by name+ext.
4.2 path.parse
Official example shown in the image below.
5 Get Relative Path
Interface: path.relative(from, to) Returns the relative path from from to to.
If from and to refer to the same location, returns an empty string.
If either argument is empty, returns the current working directory.
Example:
var path = require('path');
var p1 = path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
console.log(p1); // '../../impl/bbb'
var p2 = path.relative('/data/demo', '/data/demo');
console.log(p2); // ''
var p3 = path.relative('/data/demo', '');
console.log(p3); // '../../Users/a/.../node-path'6 Platform‑Specific Interfaces / Properties
path.posix– POSIX (Linux) implementation. path.win32 – Windows implementation. path.sep – Path separator ('/' on Linux, '\' on Windows). path.delimiter – List delimiter (':' on Linux, ';' on Windows).
When using path.win32, you may pass '/' as a separator, but the returned paths will use '\'.
Illustrated examples:
6.1 path.delimiter
Linux example:
Windows example:
7 Related Links
Official documentation: https://nodejs.org/api/path.html#path_path
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
