The path, os and URL modules

Beginner · 13 min

path.join versus path.resolve, blocking directory traversal, os for machine facts, the WHATWG URL class, and converting between file paths and file URLs.

Before thisThe file system with fs/promises

Codevolution · 13 min

The path, os and URL modules

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodevolutionReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Never build file paths by concatenating strings. `path.join` joins segments and normalizes separators and `..`; `path.resolve` produces an absolute path, treating a later absolute segment as a fresh start.
  • `path.parse`, `basename`, `dirname`, `extname` and `relative` pull paths apart. `path.sep`, `path.posix` and `path.win32` let you handle the other platform's style explicitly.
  • `path.join(base, userInput)` does not protect a directory. `../` segments climb out of it. Resolve the final path and check with `path.relative` that it still sits inside the base.
  • `os` reports facts about the machine: `availableParallelism()`, `totalmem()`, `homedir()`, `tmpdir()`, `platform()` and `EOL`. Use it to adapt to the environment, not to hard-code assumptions.
  • Use the WHATWG `URL` and `URLSearchParams` classes for parsing and building URLs. The old `url.parse()` is deprecated and unsafe. `fileURLToPath` and `pathToFileURL` convert between file paths and `file://` URLs, which ES modules use.

Why paths need a module

Windows separates path segments with a backslash, Unix with a forward slash. Segments contain .. and ., and extra slashes get doubled up when you glue strings together. '/home/' + user + '/' + file works until user ends with a slash, or the code runs on Windows. The path module exists so you describe a path by its parts and let Node produce a correct one for the platform.

path.join and path.resolve

These two are the ones you use daily, and they are not the same:

import path from 'node:path';

path.join('/a', 'b', '../c', 'file.txt');   // '/a/c/file.txt'
path.join('a', '..', '..', 'x');            // '../x'
path.resolve('/a', 'b', '..', 'c');         // '/a/c'
path.resolve('rel');                         // absolute: current working directory + 'rel'
path.join('/a', '/b', 'c');                  // '/a/b/c'
path.resolve('/a', '/b', 'c');               // '/b/c'

join concatenates the segments with the right separator and normalizes .. and .. resolve builds an absolute path, working from right to left until it has one, using the current working directory if none of the segments is absolute. That last pair shows the difference: resolve treats /b as “start again here”, like running cd /a; cd /b; cd c.

Rule of thumb: use join to assemble pieces, resolve when you need an absolute path. Anchor paths to your source files with import.meta.dirname (see ES modules in Node and interop) rather than the working directory, which depends on where the user launched the process.

Taking paths apart

path.parse('/home/u/app/index.test.js');
// { root: '/', dir: '/home/u/app', base: 'index.test.js', ext: '.js', name: 'index.test' }
path.extname('archive.tar.gz');             // '.gz'  (only the last extension)
path.basename('/x/y.js', '.js');            // 'y'
path.dirname('/a/b/c.txt');                 // '/a/b'
path.relative('/a/b/c', '/a/d');            // '../../d'
path.isAbsolute('./x');                     // false

path.sep is the platform’s separator. path.posix and path.win32 expose each style on any platform: path.win32.join('a', 'b') gives a\b even on a Mac. That matters when you handle paths from another system, such as paths inside a zip file or a Windows path in a log.

Path traversal

join does not make a path safe. Take an upload directory and a user-supplied name:

const base = '/srv/uploads';
path.join(base, '../etc/passwd');            // '/srv/etc/passwd'  -- escaped!

The .. climbs out of the directory. If that string goes to readFile, an attacker reads files you never meant to expose. The fix is to resolve and then verify the result is still inside:

function safePath(base, userInput) {
  const full = path.resolve(base, userInput);
  const rel = path.relative(base, full);
  return rel && !rel.startsWith('..') && !path.isAbsolute(rel) ? full : null;
}

safePath('/srv/uploads', 'a/b.txt');        // '/srv/uploads/a/b.txt'
safePath('/srv/uploads', '../etc/passwd');  // null
safePath('/srv/uploads', '/etc/passwd');    // null
safePath('/srv/uploads', 'a/../../x');      // null

All four cases above were run on Node 26.13.1. This is a vulnerability class, covered further in input validation and injection attacks.

The os module

node:os reports facts about the machine, which is how a program adapts to where it runs:

import os from 'node:os';

os.availableParallelism();   // how many threads you can usefully run (prefer over cpus().length)
os.totalmem();                // bytes of RAM
os.homedir();                 // the user's home directory
os.tmpdir();                  // the platform's temp directory, for use with mkdtemp
os.platform();                // 'darwin', 'linux', 'win32'
os.EOL;                       // '\n' or '\r\n'

availableParallelism() is the number to size a worker pool by (see worker threads); it respects CPU affinity and, with recent libuv, container CPU limits, which os.cpus().length does not. Use os.tmpdir() with fs.mkdtemp instead of inventing a /tmp/myapp path.

URLs

A URL is not a string to slice. Node implements the same URL and URLSearchParams classes as browsers:

const u = new URL('https://user:pw@example.com:8080/a/b?x=1&y=two#frag');
u.hostname;                  // 'example.com'
u.port;                      // '8080'
u.pathname;                  // '/a/b'
u.searchParams.get('y');     // 'two'
u.searchParams.append('z', 'a b&c');
u.href;                      // '...&z=a+b%26c#frag'  (encoding handled for you)

new URL('../up?q=1', 'https://example.com/a/b/c').href;   // 'https://example.com/a/up?q=1'
URL.canParse('nope');        // false

Building query strings with URLSearchParams handles encoding, so a b&c cannot break your query. new URL('/just/a/path') throws ERR_INVALID_URL because there is no base, and URL.canParse checks without exceptions. The legacy url.parse() still exists but prints a deprecation warning stating its behaviour is not standardized and has security implications; use URL instead.

File paths and file URLs

ES modules identify themselves with file:// URLs. Convert between the two worlds with:

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

fileURLToPath('file:///tmp/my%20file.txt');       // '/tmp/my file.txt'
pathToFileURL('/tmp/my file.txt').href;            // 'file:///tmp/my%20file.txt'

These handle encoding (%20) and Windows drive letters, which hand-written string replacement does not. Dynamic import() of a computed path on Windows needs pathToFileURL(...).href, because import('C:\\x\\y.js') is not a valid URL.

What the video covers

Codevolution’s 13-minute video is about the path module: its methods such as join, resolve, basename, dirname, extname and parse, with demos. That is the first half of this lesson. os, URL, fileURLToPath and the traversal check are in the prose, which was run against Node 26.13.1. The video is from December 2022, and path has not changed since. No transcript was available.

Where this fits

You can now describe where things are. Next, events and EventEmitter covers the pattern that streams, servers and many other core modules are built on.

Check yourself

  1. 01What do `path.join('/a', '/b', 'c')` and `path.resolve('/a', '/b', 'c')` return, and why do they differ?

    `join` returns `/a/b/c` because it just concatenates and normalizes. `resolve` returns `/b/c` because it works right to left building an absolute path, and the absolute segment `/b` discards everything before it, like `cd` commands run in sequence.

  2. 02An upload handler does `fs.readFile(path.join('/srv/uploads', req.query.name))`. What is the bug, and how do you fix it?

    A name such as `../../etc/passwd` climbs out of the upload directory, a path traversal. Resolve the combined path, compute `path.relative(base, full)`, and reject the request if the result is empty, starts with `..` or is absolute.

  3. 03Why does `new URL('/just/a/path')` throw, and how do you make it work?

    A URL needs a scheme and host unless you give it a base. Pass one: `new URL('/just/a/path', 'https://example.com')`. `URL.canParse(input, base)` checks without throwing.

  4. 04What does `fileURLToPath(import.meta.url)` do, and when do you still need it?

    It converts the `file://` URL of the current module into a normal file path, decoding things like `%20`. `import.meta.filename` does the same on Node 20.11 and later, so you need `fileURLToPath` mostly for other `file:` URLs you receive, or for older Node versions.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark