Bird
Raised Fist0
Node.jsframework~10 mins

path.parse and path.format in Node.js - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - path.parse and path.format
Input: File path string
path.parse() splits path
Object with root, dir, base, ext, name
Modify or use parts
path.format() joins parts
Output: Rebuilt path string
The flow shows how a file path string is split into parts by path.parse, then optionally modified, and finally joined back into a path string by path.format.
Execution Sample
Node.js
const path = require('path');
const parsed = path.parse('/home/user/docs/file.txt');
const formatted = path.format(parsed);
console.log(parsed);
console.log(formatted);
This code parses a file path into parts, then rebuilds it back to the original path string.
Execution Table
StepActionInputOutputNotes
1Call path.parse'/home/user/docs/file.txt'{ root: '/', dir: '/home/user/docs', base: 'file.txt', ext: '.txt', name: 'file' }Splits path into components
2Inspect parsed objectParsed objectSee parts: root, dir, base, ext, nameShows all parts separately
3Call path.formatParsed object'/home/user/docs/file.txt'Rebuilds path string from parts
4Output formatted pathFormatted string'/home/user/docs/file.txt'Matches original path
💡 All steps complete; path parsed and formatted successfully.
Variable Tracker
VariableStartAfter path.parseAfter path.formatFinal
parsedundefined{ root: '/', dir: '/home/user/docs', base: 'file.txt', ext: '.txt', name: 'file' }{ root: '/', dir: '/home/user/docs', base: 'file.txt', ext: '.txt', name: 'file' }Same object
formattedundefinedundefined'/home/user/docs/file.txt''/home/user/docs/file.txt'
Key Moments - 2 Insights
Why does path.parse return an object with both 'base' and 'name' properties?
'base' is the full file name with extension (e.g., 'file.txt'), while 'name' is just the file name without extension (e.g., 'file'). This is shown in step 1 of the execution_table.
If I change the 'name' property in the parsed object, will path.format reflect that change?
Yes, path.format uses the 'name' and 'ext' properties to build the 'base' part. Changing 'name' changes the file name in the rebuilt path, as implied in step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table step 1, what is the value of 'ext' in the parsed object?
A'/home/user/docs'
B'file.txt'
C'.txt'
D'file'
💡 Hint
Check the 'Output' column in step 1 of the execution_table.
At which step does the path string get rebuilt from parts?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look for the action 'Call path.format' in the execution_table.
If you modify the 'dir' property in the parsed object before calling path.format, what happens?
AThe rebuilt path uses the new directory path
BThe rebuilt path ignores the change
CAn error occurs
DThe file name changes
💡 Hint
Recall that path.format joins all parts including 'dir' as shown in step 3.
Concept Snapshot
path.parse(pathString) splits a path into {root, dir, base, ext, name}.
path.format(object) joins these parts back into a path string.
Use parse to inspect or modify parts.
Use format to rebuild the path.
Changing parts affects the rebuilt path.
Full Transcript
This visual execution shows how Node.js path.parse splits a file path string into an object with root, directory, base file name, extension, and name. Then path.format takes that object and rebuilds the original path string. The execution table traces each step: calling parse, inspecting the parts, calling format, and outputting the rebuilt path. Variables 'parsed' and 'formatted' track the object and string values. Key moments clarify why 'base' and 'name' differ and how modifying parts changes the rebuilt path. The quiz tests understanding of the extension property, when formatting happens, and effects of changing parts. This helps beginners see how path.parse and path.format work together to handle file paths in Node.js.

Practice

(1/5)
1. What does path.parse do in Node.js?
easy
A. It breaks a file path into parts like root, dir, base, name, and ext.
B. It combines multiple file paths into one string.
C. It reads the contents of a file at the given path.
D. It deletes a file at the specified path.

Solution

  1. Step 1: Understand the purpose of path.parse

    path.parse takes a file path string and splits it into an object with properties like root, dir, base, name, and ext.
  2. Step 2: Compare with other options

    Options A, C, and D describe different file system operations, not path parsing.
  3. Final Answer:

    It breaks a file path into parts like root, dir, base, name, and ext. -> Option A
  4. Quick Check:

    path.parse splits path into parts [OK]
Hint: Remember: parse means split path into pieces [OK]
Common Mistakes:
  • Confusing path.parse with reading file contents
  • Thinking path.parse combines paths
  • Mixing up path.parse with deleting files
2. Which of the following is the correct way to use path.format to build a path from parts?
easy
A. path.format('file.txt')
B. path.format('/home/user/file.txt')
C. path.format({ root: '/', dir: '/home/user', base: 'file.txt' })
D. path.format(['home', 'user', 'file.txt'])

Solution

  1. Step 1: Identify correct argument type for path.format

    path.format expects an object with path parts like root, dir, base, name, or ext.
  2. Step 2: Check each option

    path.format({ root: '/', dir: '/home/user', base: 'file.txt' }) correctly passes an object with root, dir, and base. Options B, C, and D pass strings or arrays, which are invalid.
  3. Final Answer:

    path.format({ root: '/', dir: '/home/user', base: 'file.txt' }) -> Option C
  4. Quick Check:

    path.format needs object with parts [OK]
Hint: path.format needs an object, not a string or array [OK]
Common Mistakes:
  • Passing a string instead of an object to path.format
  • Using an array instead of an object
  • Confusing path.format with path.parse usage
3. What is the output of this code?
const path = require('path');
const parsed = path.parse('/home/user/docs/file.txt');
console.log(parsed.base);
medium
A. '/home/user/docs/file.txt'
B. 'file.txt'
C. 'file'
D. '.txt'

Solution

  1. Step 1: Understand what path.parse returns

    path.parse returns an object with properties including base, which is the last part of the path with extension.
  2. Step 2: Check the base property for given path

    For '/home/user/docs/file.txt', base is 'file.txt'.
  3. Final Answer:

    'file.txt' -> Option B
  4. Quick Check:

    parsed.base = 'file.txt' [OK]
Hint: base is filename with extension from path.parse [OK]
Common Mistakes:
  • Confusing base with dir or name
  • Expecting full path instead of base
  • Mixing base with extension only
4. Identify the error in this code snippet:
const path = require('path');
const parts = path.parse('/var/log/sys.log');
const newPath = path.format(parts.dir + '/backup/' + parts.base);
console.log(newPath);
medium
A. path.format expects an object, but a string was passed.
B. path.parse cannot parse absolute paths.
C. The variable parts is not defined.
D. The console.log statement is missing parentheses.

Solution

  1. Step 1: Check the argument passed to path.format

    path.format requires an object with path parts, but here a string is passed by concatenating parts.dir, '/backup/', and parts.base.
  2. Step 2: Understand correct usage of path.format

    To add '/backup/' folder, modify parts.dir property or create a new object, then pass that object to path.format.
  3. Final Answer:

    path.format expects an object, but a string was passed. -> Option A
  4. Quick Check:

    path.format needs object, not string [OK]
Hint: path.format always needs an object, never a string [OK]
Common Mistakes:
  • Passing a string instead of an object to path.format
  • Assuming path.parse fails on absolute paths
  • Forgetting parentheses in console.log (not true here)
5. Given this code, what will console.log(newPath) output?
const path = require('path');
const parts = path.parse('/usr/local/bin/node');
const updatedParts = { ...parts, dir: parts.dir + '/backup' };
const newPath = path.format(updatedParts);
console.log(newPath);
hard
A. '/usr/local/bin/backup/'
B. '/usr/local/bin/node/backup'
C. '/usr/local/bin/node'
D. '/usr/local/bin/backup/node'

Solution

  1. Step 1: Analyze how updatedParts modifies dir

    updatedParts copies all parts but changes dir to parts.dir + '/backup', so dir becomes '/usr/local/bin/backup'.
  2. Step 2: Understand path.format output

    path.format builds path from updatedParts, combining dir and base ('node'), resulting in '/usr/local/bin/backup/node'.
  3. Final Answer:

    '/usr/local/bin/backup/node' -> Option D
  4. Quick Check:

    Modified dir + base = '/usr/local/bin/backup/node' [OK]
Hint: Changing dir in parts changes folder path in output [OK]
Common Mistakes:
  • Appending backup to base instead of dir
  • Confusing order of path parts
  • Forgetting to spread parts before modifying