Node.js Core ModulesLesson 3.2
Node.js path module: handling file paths correctly cross-platform
path.join, path.resolve, path.dirname, path.basename, path.extname, path.parse, path.sep, Windows vs POSIX paths
Always Use path โ Never Concatenate Strings
Manual string concatenation for file paths breaks on Windows which uses backslashes. The path module handles separators correctly on every platform.
const path = require('path');
path.join('/home', 'user', 'docs', 'file.txt');
// POSIX: /home/user/docs/file.txt
path.resolve('src', 'index.js');
// absolute path from cwd
path.dirname('/home/user/file.txt'); // /home/user
path.basename('/home/user/file.txt'); // file.txt
path.extname('/home/user/file.txt'); // .txtpath.join vs path.resolve
// path.join: concatenates with correct separator
path.join('a', 'b', 'c'); // a/b/c
// path.resolve: builds absolute path from right to left
path.resolve('a', '/b', 'c'); // /b/c (stops at absolute)
path.resolve('a', 'b'); // /cwd/a/b (prepends cwd)Parsing and Building Paths
const info = path.parse('/home/user/notes.txt');
// { root: '/', dir: '/home/user', base: 'notes.txt',
// ext: '.txt', name: 'notes' }
const rebuilt = path.format(info); // /home/user/notes.txt