The node:path module provides utilities for working with file and directory paths across different operating systems (Windows \ backslashes vs POSIX Linux / forward slashes).
path.join vs path.resolve)flowchart TD
subgraph Join ["path.join('src', 'utils', 'config.json')"]
J1["Concatenate segments with platform separator"] --> J2["Normalize relative navigation ('..')"]
end
subgraph Resolve ["path.resolve('src', 'config.json')"]
R1["Prepend Current Working Directory (CWD)"] --> R2["Build absolute root path from left to right"]
end
import path from 'node:path';
const sampleFilePath = '/var/www/kodersolution/public/index.html';
// 1. Inspect Path Components
console.log('Basename:', path.basename(sampleFilePath)); // 'index.html'
console.log('Extension:', path.extname(sampleFilePath)); // '.html'
console.log('Directory Name:', path.dirname(sampleFilePath)); // '/var/www/kodersolution/public'
// 2. Parsing & Formatting Paths
const parsedPath = path.parse(sampleFilePath);
console.log('Parsed Object:', parsedPath);
const formattedString = path.format({
dir: '/app/src',
base: 'server.js'
});
console.log('Formatted Path:', formattedString); // '/app/src/server.js'
// 3. Joining vs Resolving Paths
const relativeJoin = path.join('project', 'src', '..', 'dist', 'app.js');
console.log('Joined & Normalized Path:', relativeJoin); // 'project/dist/app.js'
const absoluteResolve = path.resolve('storage', 'uploads', 'file.png');
console.log('Absolute Resolved Path:', absoluteResolve);
// Yields full absolute path starting from current working directory
path.join() or path.resolve(): Never manually concatenate paths using string concatenation (dir + '/' + file) because Windows separators will break.__dirname in ESM: In ES Modules, __dirname is not defined by default; construct it using fileURLToPath(import.meta.url) if needed.path.posix.join() if generating URL paths intended for web browser consumption regardless of server host OS.How do you recreate __dirname in an ES Module ("type": "module") file using node:url and node:path?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With