* 해당 포스터는 생활코딩 강의를 정리한 내용입니다.
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>';
var i = 0;
while( i < filelist.length ){
list = list + `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`
i += 1
}
list = list + '</ul>';
return list;
}
var app = http.createServer(function(request,response){
var _url = request.url;
var queryData = url.parse(_url, true).query;
var pathname = url.parse(_url, true).pathname;
if( pathname === '/'){
if( queryData.id === undefined ){ //home
fs.readdir('./data', function(error, filelist) {
//* filelist의 값은 형식이 배열이다.
//→ nodejs는 어떤 특정 디렉토리에 있는 파일의 목록을 배열로 만들어서 전달한다.
var title = 'Welcome'
var description = 'Hello, Node.js'
var list = templateList(filelist);
var template = templateHTML(title,list,`<h2>${title}</h2>
<p>${description}</p>`);
response.writeHead(200);
response.end(template);
})
} else {
fs.readdir('./data', function(error, filelist) {
fs.readFile(`data/${queryData.id}`, 'utf8', function(err,description){
var list = templateList(filelist);
var title = queryData.id
var template = templateHTML(title,list,`<h2>${title}</h2>
<p>${description}</p>`);;
response.writeHead(200);
response.end(template);
});
});
}
} else {
response.writeHead(404);
response.end('Not Found');
}
});
app.listen(3000);
1. templateHTML 메소드
2. templateList 메소드
'Back-End > App' 카테고리의 다른 글
[ NodeJS - APP ] post 방식으로 전송된 데이터 받기 (0) | 2021.08.12 |
---|---|
[ NodeJS ] 패키지 매니저와 PM2 (0) | 2021.08.11 |
[ NodeJS - APP ] 글 목록 출력하기 (0) | 2021.08.10 |
[ NodeJS - APP ] Not Found 구현 + 홈 페이지 구현 (0) | 2021.08.10 |
[ NodeJS - APP ] File을 이용해서 본문 구현하기 (0) | 2021.08.10 |