White Whale Studio

[Node.js] URL Module 본문

IT Engineering/MEAN Stack

[Node.js] URL Module

glorymind 2018. 8. 30. 16:15
반응형

이번 포스팅에서는 URL 모듈을 살펴볼겁니다.

URL모듈은 웹 주소를 읽을수 있는 부분으로 나눠주는 역할을 합니다.

include를 위해서는 다음과 같이 사용합니다.


var url = require('url');

url.parse() 메서드를 사용해서 주소를 잘라서 각각의 프로퍼티로 나누어 리턴합니다.

말이 어렵네요..

예제를 보면서 살펴보겠습니다.

예를 들어 다음과 같은 주소가 있다고 합시다.

http://localhost:8080/default.htm?year=2017&month=february

기본 주소인 http://localhost:8080/default.htm 뒤에 보면

?year=2017&month=february

와 같이 있는데 나눠서 보면

year = 2017

month = february

를 나타내고 있는걸 볼수 있습니다.

이처럼 각각 파라미터를 구분하고 리턴해주는 것이 url 모듈입니다.

테스트를 해볼까요

1
2
3
4
5
6
7
8
9
10
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);
 
console.log(q.host); //returns 'localhost:8080'
console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'
 
var qdata = q.query; //returns an object: { year: 2017, month: 'february' }
console.log(qdata.month); //returns 'february'
cs

위의 소스를 실행해보면 다음과 같은 결과가 나옵니다.

위의 소스와 비교해보면서 보면

host : localhost:8080

pathname : /default.htm

search : ?year=2017&month=february

q.query : json 형식으로 리턴해주네요 (신기방기)

{ year : 2017, month : 'february' }

qdata.month 는 q.query로부터 변수를 초기화한 뒤 그 데이터 중에서도 month 데이터만 가져온것이니까 february가 되겠네요.


자, 이번에는 URL에 파일 이름 포함하여 입력하면

해당 URL의 파일이름과 동일한 파일을 찾아서 fs.readFile()로 해당 html파일을 읽어서 화면에 출력해주는 예제를 해보겠습니다.


우선 html 파일을 2개 만들어봅니다.

summer.html

winter.html

 

1
2
3
4
5
6
7
<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love the sun!</p>
</body>
</html>
cs

 

1
2
3
4
5
6
7
<!DOCTYPE html>
<html>
<body>
<h1>Winter</h1>
<p>I love the snow!</p>
</body>
</html>
cs

그리고 해당 파일들을 읽어서 화면에 출력해줄 season.js 파일을 만들어봅니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var http = require('http');
var url = require('url');
var fs = require('fs');
 
http.createServer(function (req, res) {
  var q = url.parse(req.url, true);
  var filename = "." + q.pathname;
  fs.readFile(filename, function(err, data) {
    if (err) {
      res.writeHead(404, {'Content-Type''text/html'});
      return res.end("404 Not Found");
    }  
    res.writeHead(200, {'Content-Type''text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);
cs

url에 

http://localhost:8080/summer.html 라고 입력하면

summer.html을 읽어서 화면에 보여줄것이고

http://localhost:8080/winter.html 라고 입력하면

winter.html을 읽어서 화면에 보여줄것입니다.


아무것도 입력하지 않고 http://localhost:8080/ 만 입력하면 지정된 pathname이 없기때문에 err쪽으로 빠져서 404에러 메시지를 출력합니다.


테스트를 해보니 잘 나오네요..

 http://localhost:8080/summer.html

 http://localhost:8080/winter.html

 


 








반응형

'IT Engineering > MEAN Stack' 카테고리의 다른 글

[Node.js] Events  (0) 2018.08.30
[Node.js] NPM : Node Package Manager  (0) 2018.08.30
[Node.js] File System Module  (0) 2018.08.30
[Node.js] 모듈 만들어 보기  (0) 2018.08.30
[Node.js] Start!  (0) 2018.08.30
Comments