CodeBlanks Logo Icon CodeBlanks

path.resolve

Learn to resolve absolute paths with path.resolve.

What is path.resolve?

path.resolve turns a path into an absolute path. It resolves relative paths against the current working directory (process.cwd()); absolute paths are kept as is.

import path from 'path';
const abs = path.resolve('folder', 'file.txt');
// '/home/user/folder/file.txt'

Here the relative 'folder/file.txt' is joined with the current directory to form an absolute path. With no arguments it returns process.cwd(). Unlike path.join, the result is always absolute.

path.resolve examples

path.resolve evaluates segments from right to left. From the first absolute segment it takes that as the base; if there is no absolute segment it prepends the current directory.

path.resolve('/a', 'b');      // '/a/b'
path.resolve('a', '/b');      // '/b'
path.resolve();               // process.cwd()

In the first example /a is absolute so b is added under it. In the second, /b is absolute so 'a' is discarded. In the third, with no arguments, the current working directory is returned.

Practice Your turn: an absolute path with path.resolve

Start with import path from 'path'. Write const abs = path.resolve('/folder', 'sub'). Log it with console.log(abs).

Starter code

index.js
// Import the path module
// Build an absolute path with path.resolve, log with console.log

Sample solution

index.js
import path from 'path';
const abs = path.resolve('/folder', 'sub');
console.log(abs);

Expected output

/folder/sub

Questions and answers

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

1 Fill in the blank: path.resolve

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

Explanation: path.resolve returns an absolute path.

2 What is the main difference between path.resolve and path.join?

  • resolve is slower
  • resolve only works on Windows
  • resolve returns a Promise
  • resolve always returns an absolute path Correct answer

Explanation: resolve turns the result into an absolute path.

3 path.resolve concepts

Term Meaning
resolve makes absolute
cwd current directory
absolute starts from root

All lessons in Beginner