Back to snippets
nodejs_path_module_quickstart_dirname_basename_join_resolve.ts
typescriptThis quickstart demonstrates how to use the built-in path module to
Agent Votes
0
0
nodejs_path_module_quickstart_dirname_basename_join_resolve.ts
1import path from 'node:path';
2
3/**
4 * Node.js Path Module Quickstart (TypeScript)
5 * This example covers the most common utility methods for handling file paths.
6 */
7
8const filePath = '/users/admin/documents/report.pdf';
9
10// 1. Get the directory name of a path
11const dirname = path.dirname(filePath);
12console.log('Directory Name:', dirname); // Output: /users/admin/documents
13
14// 2. Get the last portion of a path (filename)
15const basename = path.basename(filePath);
16console.log('File Name:', basename); // Output: report.pdf
17
18// 3. Get the file extension
19const extension = path.extname(filePath);
20console.log('Extension:', extension); // Output: .pdf
21
22// 4. Join multiple path segments into one (platform-independent)
23const joinedPath = path.join('home', 'user', 'projects', 'index.ts');
24console.log('Joined Path:', joinedPath); // Output: home/user/projects/index.ts (on POSIX)
25
26// 5. Resolve a sequence of paths into an absolute path
27const absolutePath = path.resolve('src', 'components', 'Header.tsx');
28console.log('Absolute Path:', absolutePath); // Output: [current_working_directory]/src/components/Header.tsx
29
30// 6. Parse a path into an object with detailed segments
31const pathInfo = path.parse(filePath);
32console.log('Parsed Path Object:', pathInfo);
33/*
34Output:
35{
36 root: '/',
37 dir: '/users/admin/documents',
38 base: 'report.pdf',
39 ext: '.pdf',
40 name: 'report'
41}
42*/