Paths and URLs

Topic 1 of 4 in Files & data6 min readIntermediateFree course

Overview

Almost every Node program works with file paths: reading templates, saving uploads, loading config, writing logs. Paths look simple, but they cause a surprising number of bugs — code that works on macOS but breaks on Windows, scripts that only work when run from one particular folder, and security holes that let users read files they shouldn’t.

The built-in path module solves all three.

Building paths

JavaScript
import path from 'node:path';

path.join('uploads', 'avatars', 'asha.png');
// 'uploads/avatars/asha.png' on macOS/Linux, 'uploads\\avatars\\asha.png' on Windows

path.join uses the right separator for the operating system and tidies up the result — removing duplicate slashes and resolving . and ..:

JavaScript
path.join('/app/', '/reports//', '../data', 'a.csv'); // '/app/data/a.csv'

Don’t build paths with string concatenation. dir + '/' + file breaks on Windows, and doubles up slashes when dir already ends with one.

join vs resolve

path.resolve always returns an absolute path. It works from right to left until it builds a complete path, and falls back to the current working directory:

JavaScript
// Run from /home/asha/app
path.resolve('reports', 'a.csv');   // '/home/asha/app/reports/a.csv'
path.resolve('/srv', 'data');       // '/srv/data'
path.join('reports', 'a.csv');      // 'reports/a.csv' (still relative)

Taking paths apart

The path /home/asha/app/reports/2026-12.csv. path.dirname gives ‘/home/asha/app/reports’, path.basename gives ‘2026-12.csv’, path.extname gives ‘.csv’, and path.basename with ‘.csv’ gives ‘2026-12’. path.join glues and tidies; path.resolve always returns an absolute path.

JavaScript
const file = '/home/asha/app/reports/2026-12.csv';

path.dirname(file);           // '/home/asha/app/reports'
path.basename(file);          // '2026-12.csv'
path.basename(file, '.csv');  // '2026-12'
path.extname(file);           // '.csv'
path.parse(file);
// { root: '/', dir: '/home/asha/app/reports', base: '2026-12.csv', ext: '.csv', name: '2026-12' }
path.format({ dir: '/tmp', name: 'backup', ext: '.zip' }); // '/tmp/backup.zip'

Other helpers:

JavaScript
path.isAbsolute('/etc/hosts');          // true
path.relative('/app/src', '/app/data'); // '../data'
path.normalize('a//b/../c');            // 'a/c'
path.sep;                               // '/' or '\\'

Where am I?

Two different “current folders” matter, and mixing them up is a classic bug.

Meaning Use it for
process.cwd() the folder the command was run from files the user points at (CLI arguments)
import.meta.dirname the folder of the current module file files that ship with your code (templates, migrations, seed data)
JavaScript
// src/email/send.js
import path from 'node:path';
import { readFile } from 'node:fs/promises';

// ✗ Works only when you run node from the project root
await readFile('src/email/templates/welcome.html', 'utf8');

// ✓ Works from anywhere
const templates = path.join(import.meta.dirname, 'templates');
await readFile(path.join(templates, 'welcome.html'), 'utf8');

import.meta.filename gives the full path of the current file. In CommonJS files the equivalents are __dirname and __filename.

File URLs

ES modules identify files with URLs like file:///home/asha/app/src/server.js — that’s what import.meta.url contains. Convert between URLs and paths with node:url:

JavaScript
import { fileURLToPath, pathToFileURL } from 'node:url';

fileURLToPath(import.meta.url);         // '/home/asha/app/src/server.js'
pathToFileURL('/srv/data/a.csv').href;  // 'file:///srv/data/a.csv'

Many fs functions accept a URL directly, so this also works:

JavaScript
const seed = new URL('./seed.json', import.meta.url);
const data = JSON.parse(await readFile(seed, 'utf8'));

Web URLs

The same global URL class from the browser parses web addresses — you’ll use it when handling HTTP requests:

JavaScript
const url = new URL('https://api.example.com/courses?level=beginner&page=2');
url.hostname;                     // 'api.example.com'
url.pathname;                     // '/courses'
url.searchParams.get('page');     // '2'
url.searchParams.set('page', '3');
url.toString();                   // '…/courses?level=beginner&page=3'

Path traversal: a real security risk

Imagine an endpoint that serves files from an uploads folder by name:

JavaScript
// ✗ Dangerous
const file = path.join('uploads', req.query.name);
res.sendFile(path.resolve(file));

A visitor asks for ?name=../../.env — and receives your secrets. This attack is called path traversal, and it’s consistently among the most common web vulnerabilities.

The defence: resolve the final path, then check it is still inside the folder you meant:

JavaScript
const UPLOADS = path.resolve(import.meta.dirname, '../uploads');

function resolveUpload(name) {
  const target = path.resolve(UPLOADS, name);
  if (!target.startsWith(UPLOADS + path.sep)) {
    throw new Error('Invalid file name');
  }
  return target;
}

Even better, don’t let users choose paths at all: store uploaded files under random IDs you generate (crypto.randomUUID()), and keep the original file name only in your database.

Treat every path that contains user input as hostile. Resolve it, check it, and only then open it.

Exercise

A safe file resolver

Write safeResolve(baseDir, userPath) that returns the absolute path of userPath inside baseDir, or throws if the result would be outside baseDir (e.g. '../../etc/passwd').

JavaScript
import path from 'node:path';

export function safeResolve(baseDir, userPath) {
  // your code here
}

Summary

  • Build paths with path.join and path.resolve, never by gluing strings with /.
  • import.meta.dirname is the folder of the current module; process.cwd() is where the command was run.
  • dirname, basename, extname and parse take paths apart.
  • Convert between file URLs and paths with fileURLToPath and pathToFileURL.
  • Never use user input in a path without checking it stays inside an allowed folder.