当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Node.js path.relative()用法及代码示例

path.relative()方法用于根据当前工作目录查找从给定路径到另一个路径的相对路径。如果两个给定路径相同,则它将解析为零长度的字符串。

用法:

path.relative( from, to )

参数:该方法接受上述和以下所述的两个参数:


  • from:该文件路径将用作基本路径。
  • to:该文件路径将用于查找相对路径。

返回值:它返回具有标准化路径形式的字符串。

以下示例程序旨在说明Node.js中的path.relative()方法:

例:

// Node.js program to demonstrate the     
// path.relative() method  
     
// Import the path module 
const path = require('path'); 
   
path1 = path.relative("geeks/website", "geeks/index.html"); 
console.log(path1) 
   
path2 = path.relative("users/admin", "admin/files/website"); 
console.log(path2) 
   
// When both the paths are same 
// It returns blank string 
path3 = path.relative("users/admin", "users/admin"); 
console.log(path3)

输出:

..\index.html
..\..\admin\files\website

参考: https://nodejs.org/api/path.html#path_path_relative_from_to



相关用法


注:本文由纯净天空筛选整理自sayantanm19大神的英文原创作品 Node.js | path.relative() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。