var http = require('http');
var fs = require('fs');
var url = require('url');
function templateHTML(title, list, body) {
return `
<!doctype html>
<html>
<head>
<title>WEB1 - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">WEB</a></h1>
${list}
${body}
</body>
</html>
`;
};
function templateList(filelist) {
var list = '<ul>';
for (var i = 0; i < filelist.length; i++) {
list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
}
list = list + '</ul>';
return list;
}
var app = http.createServer(function (request, response) {
var _url = request.url;
var pathname = url.parse(_url, true).pathname;
var queryData = url.parse(_url, true).query;
if (pathname === '/') {
// data 디렉토리 읽기 -> 파일명 가져오기
fs.readdir('./data', function(error, filelist){
// 파일 내용 읽기
fs.readFile(`data/${queryData.id}`, 'utf-8', function (err, description) {
var title = queryData.id;
if (title === undefined) {
title = 'Welcome';
description = 'Hello, Node.js';
}
var body = `<h2>${title}</h2>${description}`;
var list = templateList(filelist);
var template = templateHTML(title, list, body);
response.writeHead(200);
response.end(template);
});
});
} else {
response.writeHead(200);
response.end('Not found');
}
});
app.listen(3000);