當你手上有一個被解析過的 URL 物件,想把它重新組回一段完整的 URL 字串時,url.format 就是那把鑰匙。它與 url.parse 恰好相反,兩者猶如一對互逆的操作。
它會將一個解析後的 URL 物件,轉換成格式化的 URL 字串。
url.format(urlObj)
urlObj 為 URL 物件,可包含以下屬性:
var url = require('url');
var a = url.format({
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'
});
console.log(a);
// 輸出結果:https://example.com:8080/one?a=index&t=article&m=default
把各個片段填入物件後,format 便會自動拼裝還原成一段完整的 URL,非常適合處理動態路由或重新導向的場景。