1. 내장 URL 모듈
URL 모듈은 웹 주소를 분리 시킬 수 있다.
url.parse() 메서드를 사용하여, 속성의 각 부분들을 분리한 결과를 리턴한다.
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); //localhost:8080 리턴
console.log(q.pathname); // /default.htm 리턴
console.log(q.search); // ?year=2017&month=february 리턴
var qdata = q.query; // { year : 2017, month : 'february' } 리턴
console.log(qdata.month); // 'february' 리턴
2. Node.js 파일 서버
Node.js 가 파일 서버인 점을 인지하고, URL을 통하여 여러개의 파일들을 읽어서 보여줄 수 있다.
"demo.fileserver.js"를 작성해보자.
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);
Node 명령어로 실행하고 서버가 띄워진 상태에서 URL 을 변경하여 화면에 출력한다.
'Front-End > - Node.js' 카테고리의 다른 글
Node.js 기초 - Chapter 08. 이벤트 (0) | 2019.09.26 |
---|---|
Node.js 기초 - Chapter 07. NPM (0) | 2019.09.26 |
Node.js 기초 - Chapter 05. 파일 시스템 모듈 (0) | 2019.09.26 |
Node.js 기초 - Chapter 04. HTTP 모듈 (0) | 2019.09.26 |
Node.js 기초 - Chapter 03. 모듈(Modules) (0) | 2019.09.25 |