728x90
반응형
1. URL 모듈이란
url 모듈은 URL 문자열을 파싱하고 조작하기 위한 Node.js 내장 모듈입니다. URL의 각 구성 요소(프로토콜, 호스트, 경로, 쿼리 파라미터 등)를 분리하거나 조합할 수 있습니다. Node.js는 레거시 API와 WHATWG URL API 두 가지를 제공합니다.
2. URL의 구조
https://user:pass@www.example.com:8080/path/page?query=value#hash
│ │ │ │ │ │ │ │
│ │ │ │ │ │ │ └─ hash (fragment)
│ │ │ │ │ │ └─ search (query string)
│ │ │ │ │ └─ pathname
│ │ │ │ └─ port
│ │ │ └─ hostname
│ │ └─ password
│ └─ username
└─ protocol
3. WHATWG URL API (권장)
Node.js 7.0 이상에서 사용 가능한 최신 표준 API입니다.
3.1 URL 파싱
const { URL } = require('url');
const myUrl = new URL('https://www.example.com:8080/path/page?name=홍길동&age=30#section1');
console.log('전체 URL:', myUrl.href);
console.log('프로토콜:', myUrl.protocol); // https:
console.log('호스트:', myUrl.host); // www.example.com:8080
console.log('호스트명:', myUrl.hostname); // www.example.com
console.log('포트:', myUrl.port); // 8080
console.log('경로:', myUrl.pathname); // /path/page
console.log('쿼리:', myUrl.search); // ?name=홍길동&age=30
console.log('해시:', myUrl.hash); // #section1
console.log('origin:', myUrl.origin); // https://www.example.com:8080
3.2 쿼리 파라미터 다루기 (URLSearchParams)
const { URL } = require('url');
const myUrl = new URL('https://example.com/search?q=nodejs&page=1');
const params = myUrl.searchParams;
// 파라미터 읽기
console.log(params.get('q')); // nodejs
console.log(params.get('page')); // 1
console.log(params.get('none')); // null
// 파라미터 존재 여부 확인
console.log(params.has('q')); // true
// 모든 파라미터 순회
for (const [key, value] of params) {
console.log(`${key}: ${value}`);
}
// 파라미터 추가/수정/삭제
params.append('category', 'tech');
params.set('page', '2');
params.delete('q');
console.log(myUrl.href);
// https://example.com/search?page=2&category=tech
3.3 URL 생성 및 수정
const { URL } = require('url');
// 기본 URL로 새 URL 생성
const base = 'https://example.com';
const myUrl = new URL('/users/123', base);
console.log(myUrl.href); // https://example.com/users/123
// URL 속성 수정
myUrl.pathname = '/products/456';
myUrl.searchParams.set('sort', 'price');
myUrl.hash = 'reviews';
console.log(myUrl.href);
// https://example.com/products/456?sort=price#reviews
4. 레거시 URL API
Node.js의 전통적인 URL 파싱 방식입니다. 하위 호환성을 위해 유지되고 있습니다.
4.1 url.parse()
const url = require('url');
const myUrl = url.parse('https://www.example.com:8080/path?name=test#hash', true);
console.log(myUrl.protocol); // https:
console.log(myUrl.host); // www.example.com:8080
console.log(myUrl.hostname); // www.example.com
console.log(myUrl.port); // 8080
console.log(myUrl.pathname); // /path
console.log(myUrl.search); // ?name=test
console.log(myUrl.query); // { name: 'test' } (두 번째 인자가 true일 때)
console.log(myUrl.hash); // #hash
4.2 url.format()
const url = require('url');
const urlObject = {
protocol: 'https:',
hostname: 'example.com',
port: 8080,
pathname: '/path/to/page',
query: { name: 'test', value: '123' }
};
const urlString = url.format(urlObject);
console.log(urlString);
// https://example.com:8080/path/to/page?name=test&value=123
4.3 url.resolve()
const url = require('url');
console.log(url.resolve('https://example.com/a/b', '/c'));
// https://example.com/c
console.log(url.resolve('https://example.com/a/b', 'c'));
// https://example.com/a/c
console.log(url.resolve('https://example.com/a/b/', 'c'));
// https://example.com/a/b/c
반응형
5. 실전 활용 예시
5.1 HTTP 서버에서 URL 파싱
const http = require('http');
const { URL } = require('url');
const server = http.createServer((req, res) => {
// 전체 URL 생성
const baseUrl = `http://${req.headers.host}`;
const url = new URL(req.url, baseUrl);
console.log('경로:', url.pathname);
console.log('쿼리 파라미터:', Object.fromEntries(url.searchParams));
// 라우팅
if (url.pathname === '/api/users') {
const page = url.searchParams.get('page') || '1';
const limit = url.searchParams.get('limit') || '10';
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ page, limit }));
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(3000);
5.2 API URL 빌더
const { URL } = require('url');
function buildApiUrl(baseUrl, endpoint, params = {}) {
const url = new URL(endpoint, baseUrl);
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
url.searchParams.append(key, value);
}
});
return url.href;
}
// 사용
const apiUrl = buildApiUrl(
'https://api.example.com',
'/v1/users',
{ page: 1, limit: 20, sort: 'name' }
);
console.log(apiUrl);
// https://api.example.com/v1/users?page=1&limit=20&sort=name
5.3 URL 유효성 검사
function isValidUrl(string) {
try {
new URL(string);
return true;
} catch (err) {
return false;
}
}
console.log(isValidUrl('https://example.com')); // true
console.log(isValidUrl('not-a-url')); // false
console.log(isValidUrl('/path/to/page')); // false (상대 경로)
5.4 URL 파라미터 인코딩/디코딩
// URLSearchParams는 자동으로 인코딩/디코딩 처리
const params = new URLSearchParams();
params.set('name', '홍길동');
params.set('message', 'Hello World!');
console.log(params.toString());
// name=%ED%99%8D%EA%B8%B8%EB%8F%99&message=Hello+World%21
// 개별 인코딩/디코딩
console.log(encodeURIComponent('홍길동')); // %ED%99%8D%EA%B8%B8%EB%8F%99
console.log(decodeURIComponent('%ED%99%8D%EA%B8%B8%EB%8F%99')); // 홍길동
결론
Node.js의 url 모듈은 URL을 파싱하고 조작하기 위한 도구를 제공합니다. WHATWG URL API(new URL())가 최신 표준이며 권장되는 방식입니다. URLSearchParams를 통해 쿼리 파라미터를 쉽게 다룰 수 있고, 자동으로 인코딩/디코딩을 처리합니다. HTTP 서버에서 요청 URL을 파싱하거나 API 클라이언트에서 URL을 생성할 때 유용하게 활용됩니다.
728x90
반응형
'Node.js' 카테고리의 다른 글
| Node.js의 HTTP 모듈(http module) (0) | 2026.02.23 |
|---|---|
| Node.js의 파일 시스템 모듈(fs module) (0) | 2026.02.23 |
| Node.js의 모듈 시스템 (0) | 2026.02.22 |
| Node.js의 async/await 사용법 (0) | 2026.02.22 |
| Node.js의 프로미스(Promise) 사용법 (0) | 2026.02.22 |