Topics File System & I/O Path & URL Modules
beginner 12 min read

Path & URL Modules

Working with file paths and URLs using the built-in path and url modules.

Path Module

const path = require('path');\n\nconst filePath = '/user/docs/report.txt';\n\nconsole.log(path.basename(filePath));    // report.txt\nconsole.log(path.dirname(filePath));     // /user/docs\nconsole.log(path.extname(filePath));     // .txt\nconsole.log(path.parse(filePath));\n// { root: '/', dir: '/user/docs', base: 'report.txt', ext: '.txt', name: 'report' }\n\n// Joining paths (handles separators)\nconst fullPath = path.join(__dirname, 'data', 'config.json');\nconsole.log(fullPath);\n\n// Resolve to absolute path\nconst absPath = path.resolve('data', 'config.json');\n

URL Module

const { URL } = require('url');\n\nconst myUrl = new URL('https://api.example.com/users?id=42&role=admin');\n\nconsole.log(myUrl.hostname);      // api.example.com\nconsole.log(myUrl.pathname);      // /users\nconsole.log(myUrl.searchParams);  // URLSearchParams { 'id' => '42', 'role' => 'admin' }\nconsole.log(myUrl.searchParams.get('id')); // 42

Examples

const path = require('path');
const { URL } = require('url');

// Normalize a user-provided path
const userInput = '../../etc/passwd';
const safePath = path.resolve('/app/data', userInput);
console.log('Safe path:', path.normalize(safePath));

// Parse a URL
const url = new URL('http://localhost:3000/api/users?page=1&limit=10');
console.log('Endpoint:', url.pathname);
console.log('Page:', url.searchParams.get('page'));

// Check path security
if (!safePath.startsWith('/app/data')) {
  console.log('Path traversal detected!');
}

Your Notes

Sign in to take notes for this lesson.

Quiz

File System & I/O Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.