Node.js URL 模組:WHATWG 標準路徑與參數解析
在開發網路應用程式時,精確地解析與構建網址(URL)是基礎中的基礎。Node.js 早期使用了專有的 url.parse(),但現在推薦全面改用 WHATWG URL 標準。這不僅更安全,且與現代瀏覽器的語法完全一致。
使用全域 URL 物件
在現代 Node.js 中,URL 類別已經是全域變數,你不需要 require('url') 即可直接使用。
const myUrl = new URL('https://mike:pa55word@example.com:8080/p/a/t/h?query=node#hash');
console.log(myUrl.protocol); // https:
console.log(myUrl.username); // mike
console.log(myUrl.hostname); // example.com
console.log(myUrl.port); // 8080
console.log(myUrl.pathname); // /p/a/t/h
console.log(myUrl.search); // ?query=node
console.log(myUrl.hash); // #hash
console.log(myUrl.origin); // https://example.com:8080
處理查詢參數:URLSearchParams
這是解析網址參數(Query Strings)最優雅的方式。它提供了一群強大的方法來讀取與修改參數。
const url = new URL('https://shop.com/search?q=macbook&category=laptop');
// 1. 獲取參數
console.log(url.searchParams.get('q')); // macbook
// 2. 新增與修改 (會自動進行 URL 編碼)
url.searchParams.append('page', '1');
url.searchParams.set('q', 'iphone 15');
// 3. 排序 (對 SEO 友善,確保網址唯一性)
url.searchParams.sort();
console.log(url.toString());
// 輸出: https://shop.com/search?category=laptop&page=1&q=iphone+15
檔案路徑轉換 (ESM 必備)
在 ES Modules (ESM) 環境中,我們經常需要在「路徑字串」與「File URL」之間切換,這在讀取檔案時非常重要。
const url = require('url');
// 將 URL 轉為系統絕對路徑
const filePath = url.fileURLToPath('file:///C:/path/to/file.txt');
// 將系統路徑轉為 URL
const fileUrl = url.pathToFileURL('/usr/bin/node');
為什麼要遠離舊版 url.parse()?
如果你在舊程式碼中看到 url.parse(str),請考慮重構它。
- 安全風險:舊版 API 在解析惡意構造的網址時可能存在漏洞,導致安全繞過。
- 標準相容:WHATWG 標準是 Web 平台的通用協議,一次學習即可同時應用於 Frontend 與 Backend。
- 性能優勢:現代 URL 物件在大型應用中的內部效能經過了高度優化。
實戰:處理相對路徑
如果你只有片段路徑,可以提供一個 Base URL 來合成完整網址。
const relativePath = '../assets/logo.png';
const base = 'https://cdn.mysite.com/v1/static/';
const fullUrl = new URL(relativePath, base);
console.log(fullUrl.href); // https://cdn.mysite.com/v1/assets/logo.png
總結
- 拋棄
url.parse(),全面擁抱全域URL類別。 - 善用
URLSearchParams處理複雜的搜尋參數,它會自動幫你搞定特殊字元轉義。 - 在 ESM 環境下,利用
fileURLToPath處理檔案定位。