Chapter 8: Working with Paths and URLs
Chapter 8 of 15
Chapter 8: Working with Paths and URLs
8.1 Path Module
The path module provides utilities for working with file and directory paths. It handles cross-platform path differences.
Path Joining:
const path = require('path');
// Join path segments (handles slashes automatically)
const filePath = path.join(__dirname, 'public', 'index.html');
// Windows: C:projectpublicindex.html
// Unix: /project/public/index.html
// Resolve to absolute path
const absolutePath = path.resolve('public', 'index.html');
// Resolves from current working directory
Path Parsing:
const path = require('path');
const filePath = '/users/john/documents/file.txt';
// Get different parts of path
path.dirname(filePath); // /users/john/documents
path.basename(filePath); // file.txt
path.extname(filePath); // .txt
path.parse(filePath);
// {
// root: '/',
// dir: '/users/john/documents',
// base: 'file.txt',
// ext: '.txt',
// name: 'file'
// }
Path Utilities:
// Normalize path (remove redundant separators)
path.normalize('/foo/bar//baz/'); // /foo/bar/baz/
// Check if absolute path
path.isAbsolute('/foo/bar'); // true
path.isAbsolute('./foo'); // false
// Get relative path
path.relative('/users/john', '/users/jane'); // ../jane
8.2 URL Module
The url module provides utilities for URL resolution and parsing.
Parsing URLs:
const url = require('url');
const urlString = 'https://example.com:8080/path?query=value#hash';
const parsed = url.parse(urlString, true);
// {
// protocol: 'https:',
// host: 'example.com:8080',
// hostname: 'example.com',
// port: '8080',
// pathname: '/path',
// query: { query: 'value' },
// hash: '#hash'
// }
// Access query parameters
const queryValue = parsed.query.query; // 'value'
URL Object (Modern API):
// Using URL constructor (ES6)
const myUrl = new URL('https://example.com/path?query=value');
console.log(myUrl.hostname); // example.com
console.log(myUrl.pathname); // /path
console.log(myUrl.searchParams.get('query')); // value
// Modify URL
myUrl.searchParams.set('newParam', 'newValue');
console.log(myUrl.toString());
// https://example.com/path?query=value&newParam=newValue
URL Building:
const url = require('url');
// Build URL from parts
const urlObject = {
protocol: 'https',
host: 'example.com',
pathname: '/api/users',
query: { id: 123 }
};
const urlString = url.format(urlObject);
// https://example.com/api/users?id=123
8.3 Working with File Paths
Common operations when working with file paths.
const path = require('path');
const fs = require('fs');
// Get current file's directory
const currentDir = __dirname;
// Build path to file
const configPath = path.join(__dirname, 'config', 'settings.json');
// Check if file exists
if (fs.existsSync(configPath)) {
const config = require(configPath);
}
// Get file extension
const ext = path.extname('image.jpg'); // .jpg
// Change extension
const newPath = path.join(
path.dirname('file.txt'),
path.basename('file.txt', '.txt') + '.js'
); // file.js
8.4 Cross-Platform Considerations
Path module handles platform differences automatically.
- Use path.join() instead of string concatenation
- Don't hardcode path separators (/ or )
- Use path.resolve() for absolute paths
- Test on different platforms when possible