0
0
Node.jsframework~5 mins

path.parse and path.format in Node.js

Choose your learning style9 modes available
Introduction

These functions help you break down and build file paths easily. They make working with file locations simple and clear.

When you want to get parts like folder, file name, or extension from a full file path.
When you need to create a file path from separate parts like folder and file name.
When you want to change or check a file extension or name in a path.
When handling file paths in a program that works with files or folders.
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
This breaks the path into parts like root, dir, base, ext, and name.
Node.js
const parsed = path.parse('/home/user/file.txt');
console.log(parsed);
This builds the full path string from the directory and file name.
Node.js
const formatted = path.format({ dir: '/home/user', base: 'file.txt' });
console.log(formatted);
Works on Windows paths too, showing drive letter as root.
Node.js
const parsed = path.parse('C:\\Users\\Admin\\notes.md');
console.log(parsed);
Builds a Windows path from detailed parts.
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);
OutputSuccess
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.