CodeBlanks Logo Icon CodeBlanks

path.join

Learn to join paths with path.join.

What is path.join?

path.join joins path segments into a single path. It uses the correct separator for the operating system: \ on Windows, / on Linux and macOS.

import path from 'path';
const p = path.join('folder', 'sub', 'file.txt');
// 'folder/sub/file.txt' (on Linux)

Here three segments are joined into one path. path.join cleans redundant separators; double slashes like 'folder//sub' are fixed automatically. It is the safest way to build paths; always prefer it over manual string concatenation.

path.join examples

path.join works with both relative and absolute segments. If it sees an absolute segment, it ignores everything before it and continues from that absolute path.

path.join('/a', 'b', 'c');   // '/a/b/c'
path.join('a', '/b', 'c');   // '/b/c'

In the first example all segments join in order. In the second, since /b is absolute, 'a' is discarded and the path starts at /b. This means you must be careful building paths dynamically; user input can inject an absolute path with unexpected results.

Practice Your turn: join a path with path.join

Start with import path from 'path'. Write const p = path.join('projects', 'app', 'file.txt'). Log it with console.log(p).

Starter code

index.js
// Import the path module
// Join a path with path.join, log with console.log

Sample solution

index.js
import path from 'path';
const p = path.join('projects', 'app', 'file.txt');
console.log(p);

Expected output

projects/app/file.txt

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does path.join('a', 'b', 'c') return?

  • An array
  • A Promise
  • A single joined path Correct answer
  • It throws an error

Explanation: path.join merges segments into a single path.

2 Fill in the blank: path.join

Question
import path from 'path';
const p = path.____('folder', 'file.txt');
console.log(p);
Answer
import path from 'path';
const p = path.join('folder', 'file.txt');
console.log(p);

Explanation: You joined segments with path.join.

3 path.join properties

Term Meaning
path.join joins segments
separator OS-specific
absolute segment discards prior

All lessons in Beginner