CodeBlanks Logo Icon CodeBlanks

path.parse

Learn to parse paths with path.parse.

What is path.parse?

path.parse splits a path into its components: root, dir, base, ext and name. The returned object has these five fields.

import path from 'path';
const parsed = path.parse('/a/b/c.txt');
// { root: '/', dir: '/a/b', base: 'c.txt', ext: '.txt', name: 'c' }

Here the path is split into root, directory, file name with extension, extension, and name without extension. base gives the file name with its extension; name is just the name without the extension. parse is useful when you need to work with the path in detail.

parse components

The object returned by path.parse has five fields: root is the root directory, dir is the file's directory, base is the file name with extension, ext is the extension, and name is the name without extension.

const { name, ext } = path.parse('report.pdf');
// name: 'report', ext: '.pdf'

Here the object is destructured into two; only the wanted fields are taken. ext includes the dot ('.pdf'). This is useful when you branch by file extension.

Practice Your turn: components with path.parse

Start with import path from 'path'. Write const parsed = path.parse('/a/b/c.txt'). Log console.log(parsed.name).

Starter code

index.js
// Import the path module
// Split with path.parse, log the name field

Sample solution

index.js
import path from 'path';
const parsed = path.parse('/a/b/c.txt');
console.log(parsed.name);

Expected output

c

Questions and answers

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

1 What does the base field return in path.parse('/a/b/c.txt')?

  • 'c.txt' Correct answer
  • '/a/b'
  • '.txt'
  • 'c'

Explanation: base gives the file name with its extension.

2 Fill in the blank: path.parse

Question
import path from 'path';
const parsed = path.____('/a/b/c.txt');
console.log(parsed.name);
Answer
import path from 'path';
const parsed = path.parse('/a/b/c.txt');
console.log(parsed.name);

Explanation: path.parse splits a path into components.

3 Match the parse components

Term Meaning
root root directory
dir file directory
base name and ext
ext extension

All lessons in Beginner