• Node.js Video Tutorials

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://tutorialspoint.tw/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://tutorialspoint.tw/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://tutorialspoint.tw/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://tutorialspoint.tw/Normal-pack/Node-js

示例

如果在路徑名部分提供了任何無效的 URL 字元,則 pathname 屬性將透過對無效字元進行百分比編碼來獲取 URL。

在以下示例中,我們正在分配一個在路徑名部分包含無效字元的 URL。

const url = require('url');

const myURL = new URL("https://tutorialspoint.tw/Node`Js");
console.log(myURL.href)
console.log("Path segment of the URL: " + myURL.pathname);

輸出

正如我們在輸出中看到的,URL 中的無效字元已進行百分比編碼。

https://tutorialspoint.tw/Node%60Js
Path segment of the URL: /Node%60Js

示例

如果我們將無效的 URL 分配給 pathname 屬性,它將返回 TypeError。

在下面的示例中,我們將無效的 URL 分配給 pathname 屬性。

const url = require('url');

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

TypeError

正如我們在下面的輸出中看到的,pathname 屬性丟擲了 TypeError。

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.tutorialspoint.com/Node`Js',
  code: 'ERR_INVALID_URL'
}
nodejs_url_module.htm
廣告