Open In App

Node.js path.parse() Method

Last Updated : 13 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The path.parse() method is used to return an object whose properties represent the given path. This method returns the following properties:

  • root (root name)
  • dir (directory name)
  • base (filename with extension)
  • ext (only extension)
  • name (only filename)

The values of these properties may be different for every platform. It ignores the platform’s trailing directory separators during parsing.

Syntax:

path.parse( path )

Parameters: This method accepts single parameter path which holds the file path that would be parsed by the method. It throws a TypeError if this parameter is not a string value.

Return Value: This method returns an object with the details of the path.

Below examples illustrate the path.parse() method in node.js:

Example 1: On POSIX




// Node.js program to demonstrate the   
// path.parse() method
  
// Import the path module
const path = require('path');
   
path1 = path.parse("/users/admin/website/index.html");
console.log(path1);
   
path2 = path.parse("website/readme.md");
console.log(path2);


Output:

{
  root: '/',
  dir: '/users/admin/website',
  base: 'index.html',
  ext: '.html',
  name: 'index'
}
{
  root: '',
  dir: 'website',
  base: 'readme.md',
  ext: '.md',
  name: 'readme'
}

Example 2: On Windows




// Node.js program to demonstrate the   
// path.parse() method
  
// Import the path module
const path = require('path');
   
path1 = path.parse("C:\\users\\admin\\website\\index.html");
console.log(path1);
   
path2 = path.parse("website\\style.css");
console.log(path2);


Output:

{
  root: 'C:\\',
  dir: 'C:\\users\\admin\\website',
  base: 'index.html',
  ext: '.html',
  name: 'index'
}
{
  root: '',
  dir: 'website',
  base: 'style.css',
  ext: '.css',
  name: 'style'
}

Reference: https://nodejs.org/api/path.html#path_path_parse_path


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads