Skip to content
Related Articles

Related Articles

Node.js | path.format() Method
  • Last Updated : 20 May, 2020

The path.format() method is used to return a path string from the given path object. The method has some rules where one path property gets more priority over another:

  • The “root” parameter of the path object is ignored if the “dir” parameter is provided.
  • The “ext” and “name” parameter of the path object are ignored if the “base” parameter is provided.

Syntax:

path.format( pathObject )

Parameters: This function accepts single parameter pathObject that contains the details of the path. It has the following parameters:

  • dir: It specifies the directory name of the path object.
  • root: It specifies the root of the path object.
  • base: It specifies the base of the path object.
  • name: It specifies the file name of the path object.
  • ext: It specifies the file extension of the path object.

Return Value: It returns a path string from the provided path object.

Below programs illustrate the path.format() method in Node.js:



Example 1: On POSIX




// Import the path module
const path = require('path');
  
// CASE 1
// If "dir", "root" and "base" are all given,
// "root" is ignored.
let path1 = path.format({
    root: "/ignored/root/",
    dir: "/home/user/personal",
    base: "details.txt",
});
console.log("Path 1:", path1);
  
// CASE 2
// If "dir" is not specified then "root" will be used 
// If only "root" is provided
// platform separator will not be included.
// "ext" will be ignored.
let path2 = path.format({
    root: "/",
    base: "game.dat",
    ext: ".noextension",
});
console.log("Path 2:", path2);
  
// CASE 3
// If "base" is not specified
// "name" and "ext" will be used 
let path3 = path.format({
    root: "/images/",
    name: "image",
    ext: ".jpg",
});
console.log("Path 3:", path3);

Output:

Path 1: /home/user/personal/details.txt
Path 2: /game.dat
Path 3: /images/image.jpg

Example 2: On Windows




// Import the path module
const path = require('path');
  
// CASE 1
// If "dir", "root" and "base" are all given,
// "root" is ignored.
let path1 = path.format({
    root: "C:\\ignored\\root",
    dir: "website\\dist",
    base: "index.html",
});
console.log("Path 1:", path1);
  
// CASE 2
// If "dir" is not specified then "root"
// will be used 
// If only "root" is provided platform
// separator will not be included.
// "ext" will be ignored.
let path2 = path.format({
    root: "C:\\",
    base: "style.css",
    ext: ".ignored",
});
console.log("Path 2:", path2);
  
// CASE 3
// If "base" is not specified
// "name" and "ext" will be used 
let path3 = path.format({
    root: "website\\",
    name: "main",
    ext: ".js",
});
console.log("Path 3:", path3);

Output:

Path 1: website\dist\index.html
Path 2: C:\style.css
Path 3: website\main.js

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :