NodeJS之URL模塊html
今天講的是NodeJS裏面的一個簡單的小模塊,即url模塊;這個url模塊要使用的話,須要先引入。若只是在命令行裏好比cmd或git bash等使用url這個模塊的話,是不須要require進來的。直接使用即可git
const這個關鍵字是ES6裏面定義的常量,不能夠改變。api
1.const url = require("url");
url總共提供了三個方法,分別是url.parse(); url.format(); url.resolve();bash
1.url.parse(urlString[, parseQueryString[, slashesDenoteHost]])ui
會返回一個解析後的對象,第一個參數爲要解析的url地址,第二個參數爲是否將query字符串解析成對象格式,第三個參數來控制在沒有協議的狀況下,是否解析域名等內容url
例子1:url.parse只傳一個參數的狀況命令行
url.parse("http://user:pass@host.com:8080/p/a/t/h?query=string#hash"); /* 返回值: { protocol: 'http:', slashes: true, auth: 'user:pass', host: 'host.com:8080', port: '8080', hostname: 'host.com', hash: '#hash', search: '?query=string', query: 'query=string', pathname: '/p/a/t/h', path: '/p/a/t/h?query=string', href: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash' } 沒有設置第二個參數爲true時,query屬性爲一個字符串類型 */
例子2 : url.parse第二個參數爲true的狀況 code
url.parse("http://user:pass@host.com:8080/p/a/t/h?query=string#hash",true); /* 返回值: { protocol: 'http:', slashes: true, auth: 'user:pass', host: 'host.com:8080', port: '8080', hostname: 'host.com', hash: '#hash', search: '?query=string', query: { query: 'string' }, pathname: '/p/a/t/h', path: '/p/a/t/h?query=string', href: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash' } 返回的url對象中,query屬性爲一個對象 */
2 url.format(urlObj) orm
url.format({ protocol:"http:", host:"182.163.0:60", port:"60" }); /* 返回值: 'http://182.163.0:60' */
3.url.resolve(from, to)htm
url.resolve('http://www.baidu.com','/api/index.html'); /* 返回值: 'http://www.baidu.com/api/index.html' */
url模塊的三種方法就講到這裏了,不太全面的地方你們能夠繼續查閱其它資料哦。