Node.js path.format() Method
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
const path = require( 'path' );
let path1 = path.format({
root: "/ignored/root/" ,
dir: "/home/user/personal" ,
base: "details.txt" ,
});
console.log( "Path 1:" , path1);
let path2 = path.format({
root: "/" ,
base: "game.dat" ,
ext: ".noextension" ,
});
console.log( "Path 2:" , path2);
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
const path = require( 'path' );
let path1 = path.format({
root: "C:\\ignored\\root" ,
dir: "website\\dist" ,
base: "index.html" ,
});
console.log( "Path 1:" , path1);
let path2 = path.format({
root: "C:\\" ,
base: "style.css" ,
ext: ".ignored" ,
});
console.log( "Path 2:" , path2);
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
Last Updated :
08 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...