NodeJS - url.pathname 属性


URL 类的 NodeJS url.pathname 属性允许我们获取和设置给定 URL 的路径名段。

分配给此属性的路径名段中包含的无效 URL 字符将进行百分比编码。如果指定了无效的 URL,则此属性将引发 TypeError。

语法

以下是 URL 类的 NodeJS pathname 属性的语法


 URL.pathname

参数

此属性不接受任何参数。

返回值

此属性可以获取和设置所提供 URL 的路径名部分。

例

如果我们将一个完整的 URL 分配给 NodeJS url.pathname 属性,它将获取给定 URL 的路径名部分。

在以下示例中,我们尝试将 URL 分配给 NodeJS url.pathname 属性。


const url = require('url');

const myURL = new URL("https://www.qikepu.com/prime-pack/cloud-computing/index.asp");
console.log("Path segment of the URL: " + myURL.pathname);

输出

执行上述程序后,NodeJS pathname 属性从提供的 URL 中获取路径名段。

/prime-pack/cloud-computing/index.asp

例

如果我们尝试将路径设置为 URL,pathname 属性将返回带有提供的路径的完整 URL。

在下面的这个程序中,我们将使用 pathname 属性修改 URL 的路径。


const url = require('url');

const myURL = new URL("https://www.qikepu.com/prime-pack/cloud-computing");
console.log(myURL.href)
console.log("Path segment of the URL: " + myURL.pathname);

myURL.pathname = "/Normal-pack/Node-js";
console.log("After setting the pathname to : " + myURL.pathname);

console.log("The modified path will be: " + myURL.href);

输出

正如我们在下面的输出中所见,输入 URL 的路径已被修改。

https://www.qikepu.com/prime-pack/cloud-computing
Path segment of the URL: /prime-pack/cloud-computing

After setting the pathname to : /Normal-pack/Node-js
The modified path will be: https://www.qikepu.com/Normal-pack/Node-js

例

如果在路径名部分中提供了任何无效的 URL 字符,则 pathname 属性将通过对无效字符进行百分比编码来获取 URL。

在以下示例中,我们将分配一个在路径名部分包含无效字符的 URL。


const url = require('url');

const myURL = new URL("http://www.qikepu.com/Node`Js");
console.log(myURL.href)
console.log("Path segment of the URL: " + myURL.pathname);

输出

正如我们在输出中看到的,URL 中的无效字符被进行了百分比编码。

http://www.qikepu.com/Node%60Js
Path segment of the URL: /Node%60Js

例

如果我们将无效的 URL 分配给 pathname 属性,它将返回 TypeError。

在下面的示例中,我们将无效的 URL 分配给 pathname 属性。


const url = require('url');

const myURL = new URL("[ww.qikepu.com/Node`Js");
console.log(myURL.href)
console.log("Path segment of the URL: " + myURL.pathname);

类型错误

正如我们在下面的输出中看到的,TypeError 是由 pathname 属性抛出的。


node:internal/url:564
  throw new ERR_INVALID_URL(input);
  ^

TypeError [ERR_INVALID_URL]: Invalid URL
    at new NodeError (node:internal/errors:387:5)
    at URL.onParseError (node:internal/url:564:9)
    at new URL (node:internal/url:640:5)
    at Object.<anonymous> (C:\Users\Lenovo\Desktop\JavaScript\nodefile.js:3:15)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
    at Module.load (node:internal/modules/cjs/loader:1004:32)
    at Function.Module._load (node:internal/modules/cjs/loader:839:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  input: '[ww.qikepu.com/Node`Js',
  code: 'ERR_INVALID_URL'
}