typescriptbeginner

Cross-Platform Path Operations

Use Node.js path module for cross-platform file path manipulation, resolution, and normalization.

typescript
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.