nodejs之url模組

來源:互聯網
上載者:User

標籤:

  鄙人初步學習nodejs,目前在讀《nodejs入門》這一本書,書很小,但是讓我知道了如何用nodejs建立一個簡單的小項目。例如如何建立一個伺服器啦,例如http.createServer,還有根據不同的請求路徑來設定路由選擇啦,模組引入,建立模組啦,巴拉巴拉的東西。

現在還沒有看完這本書,看完了再來寫讀後感吧。

  今天主要記錄的是關於nodejs裡面的一個簡單的模組,url模組。這個url的模組要使用的話需要先引入。若只是在命令列裡比如cmd或git bash 等使用url這個模組的話,是不需要require進來的。直接使用便可。(我也不知道為啥不用require)

  const這個關鍵字是ES6裡面定義的常量,不可改變。

1 const url = require("url");

  url一共提供了三個方法,分別是url.parse();  url.format();  url.resolve();

  1 url.parse(urlString,boolean,boolean)

  parse這個方法可以將一個url的字串解析並返回一個url的對象

  參數:urlString指傳入一個url地址的字串

     第二個參數(可省)傳入一個布爾值,預設為false,為true時,返回的url對象中,query的屬性為一個對象。

     第三個參數(可省)傳入一個布爾值,預設為false,為true時,額,我也不知道有什麼不同,可以去看看API。

 

 

例子1,url.parse只傳一個參數的情況。

 1 url.parse("http://user:[email protected]:8080/p/a/t/h?query=string#hash"); 2 /* 3 傳回值: 4 { 5   protocol: ‘http:‘, 6   slashes: true, 7   auth: ‘user:pass‘, 8   host: ‘host.com:8080‘, 9   port: ‘8080‘,10   hostname: ‘host.com‘,11   hash: ‘#hash‘,12   search: ‘?query=string‘,13   query: ‘query=string‘,14   pathname: ‘/p/a/t/h‘,15   path: ‘/p/a/t/h?query=string‘,16   href: ‘http://user:[email protected]:8080/p/a/t/h?query=string#hash‘17  }18 沒有設定第二個參數為true時,query屬性為一個字串類型19 */

例子2,url.parse第二個參數為true的情況

 1 url.parse("http://user:[email protected]:8080/p/a/t/h?query=string#hash",true); 2 /* 3 傳回值: 4  { 5   protocol: ‘http:‘, 6   slashes: true, 7   auth: ‘user:pass‘, 8   host: ‘host.com:8080‘, 9   port: ‘8080‘,10   hostname: ‘host.com‘,11   hash: ‘#hash‘,12   search: ‘?query=string‘,13   query: { query: ‘string‘ },14   pathname: ‘/p/a/t/h‘,15   path: ‘/p/a/t/h?query=string‘,16   href: ‘http://user:[email protected]:8080/p/a/t/h?query=string#hash‘17  }18 返回的url對象中,query屬性為一個對象19 */

  2 url.format(urlObj)

  format這個方法是將傳入的url對象編程一個url字串並返回

  參數:urlObj指一個url對象

 

例子3,url.format

url.format({    protocol:"http:",    host:"182.163.0:60",    port:"60"});/*傳回值:‘http://182.163.0:60‘*/

  3 url.resolve(from,to)

  resolve這個方法返回一個格式為"from/to"的字串,在寶寶看來是對傳入的兩個參數用"/"符號進行拼接,並返回

 

 

例子4,url.resolve

url.resolve("http://whitemu.com","gulu");/*傳回值:‘http://whitemu.com/gulu‘*/

  結束語:

  好啦,對於url這個模組的總結就那麼多啦,若有什麼理解錯誤的地方還需要指正,謝謝。

nodejs之url模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.