Node.js path.format() Method
Last Updated :
08 Oct, 2021
Improve
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:
javascript
Output:
javascript
Output:
- 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.
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.
// 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);
Path 1: /home/user/personal/details.txt Path 2: /game.dat Path 3: /images/image.jpgExample 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);
Path 1: website\dist\index.html Path 2: C:\style.css Path 3: website\main.jsReference: https://nodejs.org/api/path.html#path_path_format_pathobject