nodejs
ํจ์ ์ ์ฉํ์ฌ ์ฝ๋ ์ ๋ฆฌ
byeol_dev
2023. 8. 23. 15:43
์ด์ ์ ์์ฑํ main.js ์ฝ๋ ์ ๋ฆฌ
ํจ์ ์์ฑํ์ฌ ์ค๋ณต์ฝ๋ ์ ๊ฑฐ
var http = require('http');
var fs = require('fs');
//url์ด๋ผ๋ ๋ชจ๋์ ์ฌ์ฉํ ๊ฒ์ด๋ผ๋ ์ฝ๋
var url = require('url');
//๋ณธ๋ฌธ ๋ถ๋ถ ํจ์๋ก ์ค์ ํ์ฌ ์ค๋ณต ์ ๊ฑฐ
//title, list, body๊ฐ์ ๋ฐ์ html์ ๋ฐ์
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>
`;
}
//ํ์ผ ๋ฆฌ์คํธ ๋ถ๋ฌ์์ ๊ธ๋ชฉ๋ก ์์ฑ ํจ์
//dataํด๋์ ๋ฆฌ์คํธ๋ฅผ ๋ฐ์์ 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;
}
//url์์ ๋ฐ์ดํฐ ๋ฐ๊ธฐ
//query, pathname์ ๋ฐ์์ด
//query๊ฐ์ id๋ฅผ ํฌํจํ ๊ฒฝ๋ก
//pathname์ ๊ฒฝ๋ก
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
console.log(url.parse(_url, true).pathname);
if(pathname === '/'){
//ํ ๋ถ๋ถ ์ค์
if(queryData.id === undefined){
//ํ์ผ ๋ฆฌ์คํธ ๊ฐ์ ธ์ค๊ธฐ
//readdir๋ก dataํด๋ ์์ ์๋ ๋ฐ์ดํฐ๋ฅผ ๋ถ๋ฌ์ด
fs.readdir('./data', function(error, filelist){
console.log(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){
console.log(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);