此URL.pathToFileURL函数将路径转换为文件,并确保在将给定路径转换为文件URL时正确添加/调整URL控制字符(/,\,:)。
用法:
url.pathToFileURL(path)
参数:该函数接受单个参数路径,该路径包含转换文件URL的路径。
返回值:此函数返回文件URL对象。
以下示例程序旨在说明URL.-pathToFileURL方法的使用:
范例1:
// Node program to demonstrate the
// URL.pathToFileURL API as Setter
// Importing the module 'url'
var url = require('url');
// Some random path from system
const path = 'D:\GeeksForGeeks'
// Converting the path to properly encoded file
console.log(url.pathToFileURL(path))
输出:
URL { href:'file:///D:/GeeksForGeeks', origin:'null', protocol:'file:', username:'', password:'', host:'', hostname:'', port:'', pathname:'/D:/GeeksForGeeks', search:'', searchParams:URLSearchParams {}, hash:'' }
范例2:
// Node program to demonstrate the
// URL.pathToFileURL API as Setter
// Importing the module 'url'
var url = require('url');
// Some random path from system
const path = 'D:\NodeJS\node_modules\npm'
// Converting the path to properly encoded file
console.log(url.pathToFileURL(path))
输出:
URL { href:'file:///D:/NodeJS%0Aode_modules%0Apm', origin:'null', protocol:'file:', username:'', password:'', host:'', hostname:'', port:'', pathname:'/D:/NodeJS%0Aode_modules%0Apm', search:'', searchParams:URLSearchParams {}, hash:'' }
注意:上面的程序将使用node app.js命令编译并运行。
相关用法
注:本文由纯净天空筛选整理自Abhishek7大神的英文原创作品 Node | URL.pathToFileURL API。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。