Lesson 5 of 20

Working with Paths

The path Module

The path module provides utilities for working with file and directory paths. It handles the differences between operating systems — Windows uses backslashes (\) while Linux/Mac use forward slashes (/).

Always use the path module instead of string concatenation to build file paths. This ensures your code works correctly on all operating systems.

Example
const path = require('path');

// Join path segments safely
const filePath = path.join(__dirname, 'data', 'users.json');
console.log(filePath);
// /home/user/project/data/users.json

// Resolve to an absolute path
const absolute = path.resolve('src', 'index.js');
console.log(absolute);
// /home/user/project/src/index.js

// Extract parts of a path
const file = '/home/user/project/app.js';
console.log(path.basename(file));   // 'app.js'
console.log(path.dirname(file));    // '/home/user/project'
console.log(path.extname(file));    // '.js'

// Parse a path into an object
console.log(path.parse(file));
// { root: '/', dir: '/home/user/project',
//   base: 'app.js', ext: '.js', name: 'app' }
  • path.join() — Join path segments with the correct separator
  • path.resolve() — Resolve segments into an absolute path
  • path.basename() — Get the file name from a path
  • path.dirname() — Get the directory name from a path
  • path.extname() — Get the file extension
  • path.parse() — Parse a path into its components
Notes
  • __dirname gives you the absolute path of the current file's directory. __filename gives you the full path including the file name.

Practical Path Examples

In real applications, you frequently use path with fs to read configuration files, serve static assets, or manage upload directories. Using path.join with __dirname ensures your file references work regardless of where the script is run from.

Example
const path = require('path');
const fs = require('fs').promises;

async function loadConfig() {
  // Always resolve relative to the current file
  const configPath = path.join(__dirname, 'config', 'settings.json');

  const raw = await fs.readFile(configPath, 'utf8');
  return JSON.parse(raw);
}

// Serving static files from a 'public' folder
const publicDir = path.join(__dirname, 'public');

// Get file extension to set Content-Type
function getContentType(filePath) {
  const ext = path.extname(filePath).toLowerCase();
  const types = {
    '.html': 'text/html',
    '.css': 'text/css',
    '.js': 'application/javascript',
    '.json': 'application/json',
    '.png': 'image/png',
    '.jpg': 'image/jpeg'
  };
  return types[ext] || 'application/octet-stream';
}
Notes
  • In ES Modules, __dirname is not available. Use import.meta.url with fileURLToPath instead: const __dirname = path.dirname(fileURLToPath(import.meta.url));