https://opentutorials.org/course/3332/21028
생활코딩님의 Node.js강의를 참고하였습니다.
1.모듈화
가독성, 재활용성을 높히기 위해 모듈화를 진행한다.
1-1.templateHTML(title, list, body)
HTML 페이지의 기본 구조를 반환합니다. title, list, body를 동적으로 삽입할 수 있도록 설계되었습니다.
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>
`;
}
1-2.templateList(filelist)
filelist 배열을 받아 <ul> 태그로 감싼 리스트를 생성합니다. 각 파일은 하이퍼링크로 연결되어 있습니다.
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 = i + 1;
}
list = list+'</ul>';
return list;
}
1-3.서버 생성
HTTP 서버를 생성합니다. 요청(request)을 처리하고, 응답(response)을 생성하는 콜백 함수가 포함되어 있습니다.
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){
fs.readdir('./data', function(error, filelist){
var title = 'Welcome';
var description = 'Hello, Node.js';
var list = templateList(filelist);
var template = templateHTML(title, list, `<h2>${title}</h2>${description}`);
response.writeHead(200);
response.end(template);
})
} else {
fs.readdir('./data', function(error, filelist){
fs.readFile(`data/${queryData.id}`, 'utf8', function(err, description){
var title = queryData.id;
var list = templateList(filelist);
var template = templateHTML(title, list, `<h2>${title}</h2>${description}`);
response.writeHead(200);
response.end(template);
});
});
}
} else {
response.writeHead(404);
response.end('Not found');
}
});
app.listen(3000);
반응형
'BackEnd > Node.js' 카테고리의 다른 글
[Node.js] 동기(Synchronous) ,비동기(Asynchronous) (0) | 2024.08.15 |
---|---|
[Node.js] fs.readdir 파일 목록 읽기,글목록 출력하기 (0) | 2024.08.15 |
[Node.js] 루트페이지 처리하기 (0) | 2024.08.15 |