typescriptbeginner
Cross-Platform Path Operations
Use Node.js path module for cross-platform file path manipulation, resolution, and normalization.
typescriptPress ⌘/Ctrl + Shift + C to copy
import path from 'path';
import { fileURLToPath } from 'url';
// __dirname equivalent in ESM
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Join paths safely (handles separators)
const configPath = path.join(__dirname, '..', 'config', 'settings.json');
console.log('Joined:', configPath);
// Resolve to absolute path
const absolute = path.resolve('src', 'utils', 'helpers.ts');
console.log('Resolved:', absolute);
// Parse path components
const parsed = path.parse('/home/user/docs/report.pdf');
console.log('Parsed:', parsed);
// { root: '/', dir: '/home/user/docs', base: 'report.pdf',
// ext: '.pdf', name: 'report' }
// Extract parts
console.log('Dir:', path.dirname('/a/b/c.txt')); // /a/b
console.log('Base:', path.basename('/a/b/c.txt')); // c.txt
console.log('Ext:', path.extname('/a/b/c.txt')); // .txt
console.log('No ext:', path.basename('/a/b/c.txt', '.txt')); // c
// Relative path between two locations
const from = '/home/user/projects/app';
const to = '/home/user/shared/libs';
console.log('Relative:', path.relative(from, to));
// ../../shared/libs
// Normalize messy paths
const messy = '/foo/bar//baz/asdf/quux/..';
console.log('Normalized:', path.normalize(messy));
// /foo/bar/baz/asdf
// Build path from components
const built = path.format({
dir: '/home/user',
name: 'config',
ext: '.json',
});
console.log('Built:', built); // /home/user/config.json
// Check if path is absolute
console.log('Is absolute /foo:', path.isAbsolute('/foo')); // true
console.log('Is absolute foo:', path.isAbsolute('foo')); // false
// Platform-specific separator
console.log('Separator:', path.sep); // / or \
console.log('Delimiter:', path.delimiter); // : or ;Use Cases
- Cross-platform file path handling
- ESM __dirname replacement
- Path component extraction
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
Directory Operations with fs
Create, read, copy, and remove directories recursively using Node.js fs/promises.
Best for: Build tool directory management
#nodejs#fs
typescriptadvanced
Node.js Worker Threads for Parallel Processing
Use Worker Threads to run CPU-intensive tasks in parallel without blocking the event loop.
Best for: CPU-intensive data processing without blocking
#nodejs#worker-threads
typescriptintermediate
Node.js Stream Pipeline with Transform
Build efficient data processing pipelines using Node.js streams for large file handling.
Best for: Processing large CSV files without loading into memory
#nodejs#streams
typescriptintermediate
TypeScript Typed Event Emitter
Create type-safe event emitters in Node.js with full TypeScript support and autocomplete.
Best for: Type-safe pub/sub communication between modules
#nodejs#events