Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- OOP
- bean
- puppeteer
- 인접리스트
- 프로그래머스
- Kubernetes
- Interceptor
- css
- typescript
- Spring
- GraphQL
- 탐욕법
- LifeCycle
- REST API
- TIL
- winston
- nestjs
- 코딩테스트
- JWT
- 인접행렬
- node.js
- html
- javascript
- 자료구조
- Linux
- Deep Dive
- MySQL
- 알고리즘
- dfs
- java
Archives
- Today
- Total
처음부터 차근차근
Node.js 함수를 이용해서 main.js 정리정돈하기 본문
728x90
반복되는 코드는 함수를 이용하여 정리해 줄 수 있다.
현재 두 부분의 코드가 반복해서 보이는데
templateHTML, templateList를 통해 정리해보자.
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 = 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){
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);
함수를 정리해줬더니, 본문 코드가 굉장히 깔끔해졌다.
'FrameWork > Node.js' 카테고리의 다른 글
Node.js App에서 Create 진행해보기 (0) | 2023.05.31 |
---|---|
Node.js Synchronous & Asynchronous (0) | 2023.05.30 |
Node.js 파일 리스트 읽어오기 (0) | 2023.05.30 |
Node.js 홈페이지 구현 (0) | 2023.05.30 |
Node.js Not found 구현 (0) | 2023.05.30 |