These functions help you break down and build file paths easily. They make working with file locations simple and clear.
path.parse and path.format in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
const path = require('path'); // To break a path into parts const parsed = path.parse(pathString); // To build a path from parts const formatted = path.format(pathObject);
path.parse takes a string path and returns an object with parts like root, dir, base, ext, and name.
path.format takes an object with path parts and returns a full path string.
Examples
Node.js
const parsed = path.parse('/home/user/file.txt');
console.log(parsed);Node.js
const formatted = path.format({ dir: '/home/user', base: 'file.txt' });
console.log(formatted);Node.js
const parsed = path.parse('C:\\Users\\Admin\\notes.md');
console.log(parsed);Node.js
const formatted = path.format({ root: 'C:\\', dir: 'C:\\Users\\Admin', name: 'notes', ext: '.md' });
console.log(formatted);Sample Program
This program breaks a file path into parts, changes the file extension, then builds a new path with the updated extension.
Node.js
const path = require('path'); // Example path string const filePath = '/home/user/docs/report.pdf'; // Parse the path into parts const parts = path.parse(filePath); // Show the parts console.log('Parsed parts:', parts); // Change the extension parts.ext = '.txt'; parts.base = parts.name + parts.ext; // Build a new path with changed extension const newPath = path.format(parts); console.log('New path:', newPath);
Important Notes
Remember to update both ext and base when changing the file extension.
On Windows, paths use backslashes \, but Node.js handles both styles well.
Use path.parse to safely get parts instead of splitting strings manually.
Summary
path.parse breaks a file path into useful parts.
path.format builds a file path from parts.
These help manage file paths clearly and safely in Node.js programs.
Practice
1. What does
path.parse do in Node.js?easy
Solution
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.Step 2: Compare with other options
Options A, C, and D describe different file system operations, not path parsing.Final Answer:
It breaks a file path into parts like root, dir, base, name, and ext. -> Option AQuick 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
Solution
Step 1: Identify correct argument type for path.format
path.format expects an object with path parts like root, dir, base, name, or ext.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.Final Answer:
path.format({ root: '/', dir: '/home/user', base: 'file.txt' }) -> Option CQuick 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
Solution
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.Step 2: Check the base property for given path
For '/home/user/docs/file.txt', base is 'file.txt'.Final Answer:
'file.txt' -> Option BQuick 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
Solution
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.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.Final Answer:
path.format expects an object, but a string was passed. -> Option AQuick 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
Solution
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'.Step 2: Understand path.format output
path.format builds path from updatedParts, combining dir and base ('node'), resulting in '/usr/local/bin/backup/node'.Final Answer:
'/usr/local/bin/backup/node' -> Option DQuick 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
