Thuta Learning
Node.js
IntermediateWeb DevelopmentBeginner

Path Module

Node.jsLesson 825 min

What you'll walk away with

  • Predict the different results of path.join() and path.resolve()
  • Take a path apart with basename(), dirname(), extname() and parse()
  • Explain when to use path.posix or path.win32, and what __dirname is
  • Use path.relative() to detect a user-supplied path escaping a root folder

Explain it simply

Explain it simply

A file path is a set of directions to a file: "go into shop, then uploads, then take profile.png". The trouble is that operating systems write those directions differently. Linux and macOS separate folders with /, while Windows uses \ and adds a drive letter such as C:.

The path module is like a clerk who writes those directions in the current OS's style. Give it folder names and it joins them with the right separator, cleans up confusing . and .. parts, and pulls the file name, folder and extension out of an existing path. Nothing needs installing: it ships with Node.js.

Problem → Why → Solution

The problem: building paths by gluing strings

Say you are writing a feature that serves uploaded pictures. The quick way is to join the folder and file name with +. Then one teammate puts a trailing / on the base and you get a double //, while another leaves it off and the folder and file names run together. Worse, nobody checks the file name the user sent, so input like ../../etc/passwd climbs out of uploads and reads other files on the server.

avatar.js
const base = '/srv/shop/uploads';

// Works only if everyone agrees on slashes
const a = base + '/' + 'profile.png';   // '/srv/shop/uploads/profile.png'
const b = base + 'profile.png';         // '/srv/shop/uploadsprofile.png'  (bug)

// Trusting user input: this walks right out of uploads
const userFile = '../../../etc/passwd';
const c = base + '/' + userFile;        // reads /etc/passwd on the server

Why is string concatenation not enough?

A string knows nothing about path rules: how many separators belong between parts, whether .. means "go up one folder", or whether this OS uses / or \. The path module knows those rules and normalizes for you. But path.join() alone does not stop a ../ attack: you still have to resolve the path and then check yourself that it stayed inside the root.

Core concept: build, take apart, check

path.join(...segments) glues the parts with the platform separator and normalizes the result. Normalizing means collapsing repeated separators such as //, dropping . parts, and letting each .. cancel the folder before it. join works purely on the strings you give it: it never checks that a file exists on disk, and the result may be relative or absolute.

path.resolve(...segments) always returns an absolute path. It works from right to left until it has an absolute path, so an absolute segment such as /etc in the middle makes it ignore every segment before it. If no segment is absolute, it starts from process.cwd(), the folder the program was launched from. That is why resolve('data.json') can give different answers depending on where you opened the terminal.

To avoid that problem, CommonJS files use __dirname: the absolute path of the folder containing the current .js file, which stays the same wherever you run the program from. ES modules (.mjs files or "type": "module") have no __dirname; since Node 20.11 you can use import.meta.dirname instead.

Four functions take a path apart. basename() gives the last part (the file name), and a second argument such as '.png' strips that extension. dirname() gives the containing folder, extname() gives the extension starting at the last dot, and parse() returns all of these in one object.

FunctionResult for '/srv/shop/uploads/profile.png'
basename(p)'profile.png'
basename(p, '.png')'profile'
dirname(p)'/srv/shop/uploads'
extname(p)'.png'
parse(p){ root, dir, base, ext, name }

Finally, path.relative(from, to) tells you how to walk from one location to another. If to is inside from, the answer is something plain like uploads/profile.png; if it is outside, the answer starts with ... That small fact is the foundation of the security check later in this lesson.

Mental model: build, resolve, verify
  1. Start from a trusted base folder
  2. join/resolve into an absolute path
  3. Check it with relative() vs the root
  4. Only then open the file with fs

The path module only does arithmetic on strings and never touches the disk; whether the file exists is fs's job.

General pattern

javascript
const path = require('path');      // ESM: import path from 'node:path';

path.join(base, 'folder', 'file.ext');   // glue + normalize
path.resolve(base, input);               // always absolute, right to left
path.relative(from, to);                 // '..' prefix = outside 'from'

path.basename(p, ext); path.dirname(p); path.extname(p); path.parse(p);

path.posix.join(...parts);               // always '/' separators
path.win32.join(...parts);               // always '\\' and drive letters

Normally you call path.join() and path.resolve() directly and get the current OS's style. When you need one specific style, for example building URL paths or keeping test output identical everywhere, use path.posix or path.win32.

Example: building a path and taking it apart

This example uses a fixed base, '/srv/shop', and prints with path.posix, so the output is the same whether you run it on Windows or Linux. In a real project the base usually comes from __dirname and you call path directly instead of path.posix. The last line shows path.win32 turning even forward slashes into Windows style.

paths.js
const path = require('path');

// A fixed base keeps this output identical on every computer.
// In a real project the base usually comes from __dirname.
const base = '/srv/shop';

const avatar = path.posix.join(base, 'uploads', 'avatars', '..', 'profile.png');
console.log('join     :', avatar);
console.log('basename :', path.posix.basename(avatar));
console.log('name     :', path.posix.basename(avatar, '.png'));
console.log('dirname  :', path.posix.dirname(avatar));
console.log('extname  :', path.posix.extname(avatar));

console.log('resolve  :', path.posix.resolve(base, 'public', 'css/site.css'));
console.log('abs wins :', path.posix.resolve(base, '/etc', 'hosts'));
console.log('relative :', path.posix.relative(base, avatar));
const outside = path.posix.resolve(base, '../../etc');
console.log('escape   :', path.posix.relative(base, outside));

console.log('windows  :', path.win32.join('C:/shop', 'uploads', 'profile.png'));

Code breakdown

  1. join + normalizeconst avatar = path.posix.join(base, 'uploads', 'avatars', '..', 'profile.png');

    The '..' cancels 'avatars' before it, so the result is /srv/shop/uploads/profile.png. join inserts the separators itself, so you never type a / by hand.

  2. Taking it apartconsole.log('name :', path.posix.basename(avatar, '.png'));

    Passing the extension to basename strips it and returns just 'profile', which is handy when you want to derive a name such as profile-small.png.

  3. resolveconsole.log('abs wins :', path.posix.resolve(base, '/etc', 'hosts'));

    '/etc' is absolute, so resolve starts over from there and ignores base completely. Feed raw user input into resolve and it can skip your base the same way.

  4. relative as a detectorconsole.log('escape :', path.posix.relative(base, outside));

    For a path inside base, relative() gives 'uploads/profile.png'; for one that escaped, it gives '../../etc', which starts with ...

  5. win32 on any OSconsole.log('windows :', path.win32.join('C:/shop', 'uploads', 'profile.png'));

    path.win32 follows Windows rules even when running on Linux, turning / into \. It is useful for testing tools that must handle Windows paths.

You should see
join     : /srv/shop/uploads/profile.png
basename : profile.png
name     : profile
dirname  : /srv/shop/uploads
extname  : .png
resolve  : /srv/shop/public/css/site.css
abs wins : /etc/hosts
relative : uploads/profile.png
escape   : ../../etc
windows  : C:\shop\uploads\profile.png

Checking a user-supplied path safely

Anywhere a user sends a file name, such as a download link, a file manager or a static server, you must guard against "path traversal". The reliable method has three steps: resolve the root and the input into an absolute path, compute relative() from the root to that path, and reject it if the result is .., starts with ../, or is itself absolute (which happens on Windows when the drive differs).

inside.js
const path = require('path');

function isInside(root, target) {
  const rel = path.relative(root, target);
  return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
}

console.log(isInside('/srv/shop', '/srv/shop/uploads/a.png'));
console.log(isInside('/srv/shop', '/srv/shop-backup/a.png'));

A startsWith(root) check is not safe

'/srv/shop-backup/a.png'.startsWith('/srv/shop') is true, yet shop-backup is a different folder. relative() correctly reports '../shop-backup/a.png'. (startsWith('..') also rejects a file literally named '..notes.txt', but that errs on the safe side.)

In real projects

Where this shows up in real projects

In an Express app, path turns up almost everywhere. express.static(path.join(__dirname, 'public')) points at the static folder, the view engine is told where templates live, and uploaded files get a destination path inside an uploads folder. Starting from __dirname means the app finds its files whether it is launched from the project root, by PM2 or inside a Docker container.

Build tools and CLIs lean on path heavily too: extname() picks out the .md files, basename() derives output names, and relative() prints friendly paths such as "src/pages/about.md" in logs. Any server that accepts paths from users keeps the resolve-plus-relative check in one helper next to where files are opened, and every route calls that helper.

Common mistakes

Common mistakes

1. Forgetting that resolve depends on the cwd

path.resolve('data/users.json') works when you run node app.js inside the project folder, then fails to find the file when someone runs node project/app.js from elsewhere. For files that belong to the program, use path.join(__dirname, 'data', 'users.json'), which does not care where the process was started.

2. Believing join protects against traversal

path.join(uploads, '../../etc/passwd') does normalize, but the result still points at /etc/passwd outside uploads. Normalizing is not validating; you still need the relative() check.

3. Using __dirname inside an ES module

After adding "type": "module", using __dirname throws "ReferenceError: __dirname is not defined in ES module scope". Use import.meta.dirname (Node 20.11+) or fileURLToPath(new URL('.', import.meta.url)).

Best practices

Best practices

  • Never glue disk paths with +; always use path.join() or path.resolve().
  • URL paths such as /products/15 always use /, so build them with path.posix or the URL class.
  • Check every path that comes from user input with resolve plus relative, in one helper that opens files.

Mini challenge

Mini challenge: safeResolve()

Write safeResolve(root, userPath), which returns the absolute path when the user's path stays inside the uploads root and throws an error when it escapes.

  • Compute the absolute path with path.posix.resolve()
  • Decide inside/outside from the result of path.posix.relative()
  • Reject a relative result that is '..', starts with '../', or is absolute
  • Try five inputs and print OK or BLOCKED for each
safe-resolve.js
const path = require('path');

function safeResolve(root, userPath) {
  // TODO: resolve root + userPath into an absolute path
  // TODO: compute the path relative to root
  // TODO: throw an Error when it escapes root, otherwise return the path
}

const root = '/srv/shop/uploads';
const inputs = ['cat.png', 'avatars/../dog.png', '../../etc/passwd',
  '/etc/passwd', '../uploads-old/a.png'];

// TODO: for each input print "OK      <path>" or "BLOCKED <input>"

Expected: Expected output: OK /srv/shop/uploads/cat.png OK /srv/shop/uploads/dog.png BLOCKED ../../etc/passwd BLOCKED /etc/passwd BLOCKED ../uploads-old/a.png

Show hint

Resolving an absolute input ('/etc/passwd') ignores the root, but its relative() result starts with .., so the same check catches it. Catch the thrown error with try/catch.

Show solution
safe-resolve.js
const path = require('path');

function safeResolve(root, userPath) {
  const target = path.posix.resolve(root, userPath);
  const rel = path.posix.relative(root, target);
  if (rel === '..' || rel.startsWith('../') || path.posix.isAbsolute(rel)) {
    throw new Error(`Path escapes root: ${userPath}`);
  }
  return target;
}

const root = '/srv/shop/uploads';
const inputs = ['cat.png', 'avatars/../dog.png', '../../etc/passwd',
  '/etc/passwd', '../uploads-old/a.png'];

for (const input of inputs) {
  try {
    console.log('OK     ', safeResolve(root, input));
  } catch {
    console.log('BLOCKED', input);
  }
}

Quick quiz 1 / 3

What does path.posix.resolve('/srv/app', 'public', '/tmp', 'a.txt') return?

Quick quiz 2 / 3

For root '/data', which check wrongly allows '/data-old/x.txt'?

Quick quiz 3 / 3

In server.js of a project with "type": "module", what does console.log(__dirname) do?

What to remember

  • path.join() glues segments with the OS separator and normalizes; path.resolve() always returns an absolute path.
  • basename, dirname, extname and parse take a path apart.
  • Locate your program's files from __dirname (import.meta.dirname in ESM), not from the cwd.
  • Resolve user-supplied paths and reject them when relative() starts with ...

Path — Node.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Path Module | Thuta Learning