Skip to content

URL Module

URL คืออะไร? ทำไมต้องแยก/จัดการ URL?

URL คือที่อยู่ของข้อมูลหรือ resource บนอินเทอร์เน็ต เช่น example.com faviconhttps://example.com/api มือใหม่ควรรู้วิธีแยก/จัดการ URL เพราะใช้บ่อยใน web server, API, และงานที่เกี่ยวกับ network

  • การแยก query string, path, hostname จำเป็นกับ web/API
  • URL module ทำให้จัดการ URL ได้ง่ายและปลอดภัย
  • เหมาะกับมือใหม่ที่อยากเข้าใจการสื่อสารข้อมูลบนเว็บ

แนะนำ URL module

url เป็น built-in module สำหรับแยก, สร้าง, และจัดการ URL ได้อย่างง่ายดายใน Node.js

ฟังก์ชันหลักที่ใช้บ่อย

new URL(input[, base])

สร้าง URL object จาก string

js
const myURL = new URL("https://example.com:8000/path/name?query=123");
console.log(myURL.hostname); // example.com

url.parse(urlString)

(เวอร์ชันเก่า) แยกส่วนประกอบของ URL

js
const url = require("url");
const parsed = url.parse("https://example.com/path?foo=bar");
console.log(parsed.pathname); // /path

url.format(URLObject)

แปลง URL object กลับเป็น string

js
const url = require("url");
const obj = { protocol: "https:", host: "example.com", pathname: "/foo" };
console.log(url.format(obj)); // https://example.com/foo

กรณีใช้งานจริง

  • ตรวจสอบ/แยก query string จาก URL
  • สร้างลิงก์ redirect หรือ API endpoint

อ้างอิง