본문 바로가기

JavaScript/Node.js

url 모듈

728x90

url 모듈 정의

url 모듈을 통해서 URL 문자열을 객체로 바꾸거나 URL 객체를 문자열로 변환 가능하며,
파싱과 조합을 사용하여 URL과 관련된 정보를 가져올 수 있습니다.


url 모듈 함수

  • parse(urlStr, [, parseQueryString=false, slashesDenoteHost=false])) : URL 문자열을 URL 객체로 변환하여 리턴합니다.
  • format(urlObj) : URL 객체를 URL 문자열로 변환하여 리턴합니다.
  • resolve(from, to) : 매개변수를 조합하여 URL 문자열을 생성하여 리턴합니다.

예제

'http://user:pass@host.com:8080/p/a/t/h?query=string#hash' 주소를 객체로 쪼게어 본다면 다음과 같다고 한다.

┌─────────────────────────────────────────────────────────────────────────────┐
│                                    href                                     │
├──────────┬┬───────────┬─────────────────┬───────────────────────────┬───────┤
│ protocol ││   auth    │      host       │           path            │ hash  │
│          ││           ├──────────┬──────┼──────────┬────────────────┤       │
│          ││           │ hostname │ port │ pathname │     search     │       │
│          ││           │          │      │          ├─┬──────────────┤       │
│          ││           │          │      │          │ │    query     │       │
"  http:   // user:pass @ host.com : 8080   /p/a/t/h  ?  query=string   #hash "
│          ││           │          │      │          │ │              │       │
└──────────┴┴───────────┴──────────┴──────┴──────────┴─┴──────────────┴───────┘
(all spaces in the "" line should be ignored -- they are purely for formatting)

이렇게 파싱된 url 객체를 잘 활용할 수 있을 뿐더러, resolve, format 함수를 통해 조합하고 다시 url 객체로 변경할 수도 있다.

[출처]
https://lacommune.tistory.com/125

728x90