1. 程式人生 > 程式設計 >使用node.JS中的url模組解析URL資訊

使用node.JS中的url模組解析URL資訊

在HTTP部分,詳細介紹了URL的相關知識。而nodejs中的url模組提供了一些實用函式,用於URL處理與解析。

解析URL

解析 URL 物件有以下內容,依賴於他們是否在 URL 字串裡存在。任何不在 URL 字串裡的部分,都不會出現在解析物件裡

'http://user:[email protected]:8080/p/a/t/h?query=string#hash'

┌─────────────────────────────────────────────────────────────────────────────┐

│                                    href                                     │

├──────────┬┬───────────┬─────────────────┬───────────────────────────┬───────┤

│ protocol ││   auth    │      host       │           path            │ hash  │

│          ││           ├──────────┬──────┼──────────┬────────────────┤       │

│          ││           │ hostname │ port │ pathname │     search     │       │

│          ││           │          │      │          ├─┬──────────────┤       │

│          ││           │          │      │          │ │    query     │       │

"  http:   // user:pass @ host.com : 8080   /p/a/t/h  ?  query=string   #hash "

│          ││           │          │      │          │ │              │       │

└──────────┴┴───────────┴──────────┴──────┴──────────┴─┴──────────────┴───────┘

href: 準備解析的完整的 URL,包含協議和主機(小寫)

'http://user:[email protected]:8080/p/a/t/h?query=string#hash'

protocol: 請求協議, 小寫

'http:'

slashes: 協議要求的斜槓(冒號後)

true 或 false

host: 完整的 URL 小寫 主機部分,包含埠資訊

'host.com:8080'

auth: url 中的驗證資訊

'user:pass'

hostname: 域名中的小寫主機名

'host.com'

port: 主機的埠號

'8080'

pathname: URL 中的路徑部分,在主機名後,查詢字元前,包含第一個斜槓

'/p/a/t/h'

search: URL 中的查詢字串,包含開頭的問號

'?query=string'

path: pathname 和 search 連在一起

'/p/a/t/h?query=string'

query: 查詢字串中得引數部分,或者使用 querystring.parse() 解析後返回的物件

'query=string' or {'query':'string'}

hash: URL 的 “#” 後面部分(包括 # 符號)

'#hash'

URL方法

URL模組包含分析和解析 URL 的工具。呼叫 require('url') 來訪問模組

var url = require('url');
/*
{ parse: [Function: urlParse],resolve: [Function: urlResolve],resolveObject: [Function: urlResolveObject],format: [Function: urlFormat],Url: [Function: Url] }
 */
console.log(url);
url.parse(urlStr[,parseQueryString][,slashesDenoteHost])

輸入 URL 字串,返回一個物件

第二個引數parseQueryString(預設為false),如為false,則urlObject.query為未解析的字串,比如author=%E5%B0%8F%E7%81%AB%E6%9F%B4,且對應的值不會decode;如果parseQueryString為true,則urlObject.query為object,比如{ author: '小火柴' },且值會被decode

第三個引數slashesDenoteHos(預設為false),如果為true,可以正確解析不帶協議頭的URL,類似//foo/bar裡的foo就會被認為是hostname;如果為false,則foo被認為是pathname的一部分

var url = require('url');
var str = 'http://user:[email protected]:8080/p/a/t/h?author=%E5%B0%8F%E7%81%AB%E6%9F%B4#hash';
/*
Url {
 protocol: 'http:',slashes: true,auth: 'user:pass',host: 'host.com:8080',port: '8080',hostname: 'host.com',hash: '#hash',search: '?author=%E5%B0%8F%E7%81%AB%E6%9F%B4',query: 'author=%E5%B0%8F%E7%81%AB%E6%9F%B4',pathname: '/p/a/t/h',path: '/p/a/t/h?author=%E5%B0%8F%E7%81%AB%E6%9F%B4',href: 'http://user:[email protected]:8080/p/a/t/h?author=%E5%B0%8F%E7%81%AB%E6%9F%B4#hash' }
 */
console.log(url.parse(str));
var url = require('url');
var str = 'http://user:[email protected]:8080/p/a/t/h?author=%E5%B0%8F%E7%81%AB%E6%9F%B4#hash';
/*
Url {
 protocol: 'http:',query: { author: '小火柴' },href: 'http://user:[email protected]:8080/p/a/t/h?author=%E5%B0%8F%E7%81%AB%E6%9F%B4#hash' }
 */
console.log(url.parse(str,true));
var url = require('url');
var str = '//foo/bar';
var result1 = url.parse(str,true);
var result2 = url.parse(str,true,true);
console.log(result1.path);//'//foo/bar'
console.log(result1.pathname);//'//foo/bar'
console.log(result1.hostname);//null
console.log(result2.path);//'/bar'
console.log(result2.pathname);//'/bar'
console.log(result2.hostname);//'foo'

url.format(urlObject)

url.parse(str)的反向操作,輸入一個解析過的 URL 物件,返回格式化過的字串

urlObject包含了很多欄位,比如protocol、slashes、protocol等,且不一定需要全部傳,所以有一套解析邏輯

格式化的工作流程如下

href 會被忽略

protocol 無論是否有末尾的 : (冒號),會同樣的處理

http,https,ftp,gopher,file 協議會被新增字尾://

mailto,xmpp,aim,sftp,foo,等協議新增字尾:

slashes 如果協議需要 ://,設定為 true

僅需對之前列出的沒有斜槓的協議,比如議 mongodb://localhost:8000/

auth 如果出現將會使用.

hostname 僅在缺少 host 時使用

port 僅在缺少 host 時使用

host 用來替換 hostname 和 port

pathname 無論結尾是否有 / 將會同樣處理

search 將會替代 query屬性

無論前面是否有 / 將會同樣處理

query (物件; 參見 querystring) 如果沒有 search,將會使用

hash 無論前面是否有#,都會同樣處理

var url = require('url');
var obj = {
 protocol: 'http:',query: { author: '小火柴' }
}
//http://user:[email protected]:8080?author=%E5%B0%8F%E7%81%AB%E6%9F%B4#hash
console.log(url.format(obj));

url.resolve(from,to)

url.resolve()方法以一種瀏覽器解析超連結的方式把一個目標URL解析成相對於一個基礎URL,引數如下

from <String> 解析時相對的基本 URL。

to <String> 要解析的超連結 URL。

var url = require('url');
console.log(url.resolve('/one/two/three','four'));     // '/one/two/four'
console.log(url.resolve('http://example.com/','/one'));  // 'http://example.com/one'
console.log(url.resolve('http://example.com/one','/two')); // 'http://example.com/two'

更多關於node.JS中url模組的使用方法大家可參考下面的相關連結