想從一段 URL 字串中取出協議、主機、路徑、查詢參數等各個部分嗎?url.parse 正是為此而生,它能將字串轉換為結構化的物件,方便你逐一取用。
它會把一個 URL 字串轉換成物件並回傳,是 url.format 的逆操作。
url.parse(urlStr, [parseQueryString], [slashesDenoteHost])
//foo/bar 形式的字串會被解析成 { pathname: '//foo/bar' };若設為 true,則會被解析成 { host: 'foo', pathname: '/bar' }。var url = require('url');
var a = url.parse('https://example.com:8080/one?a=index&t=article&m=default');
console.log(a);
// 輸出結果:
{
protocol : 'http' ,
auth : null ,
host : 'example.com:8080' ,
port : '8080' ,
hostname : 'example.com' ,
hash : null ,
search : '?a=index&t=article&m=default',
query : 'a=index&t=article&m=default',
pathname : '/one',
path : '/one?a=index&t=article&m=default',
href : 'https://example.com:8080/one?a=index&t=article&m=default'
}
透過這個物件,你就能輕鬆取得協議、埠、路徑與查詢字串等各項資訊,是處理 URL 時非常實用的基礎工具。