대딩코딩/웹개발 스터디
[Node.js] 8. 글목록 출력
시데브
2023. 11. 16. 21:56
해당 게시물은 유튜브 생활코딩 "Node.js" 강의 영상을 참고했습니다.
(https://www.youtube.com/watch?v=3RS_A87IAPA&list=PLuHgQVnccGMA9QQX5wqj6ThK7t2tsGxjm&index=1)
파일목록 출력
var testFolder = './data'; //'.': 터미널의 현재 위치 기준
var fs = require('fs');
fs.readdir(testFolder, function(error, filelist) {
console.log(filelist);
})
[ 'CSS', 'HTML', 'JavaScript' ]
>> 현 터미널 위치/data 경로의 파일 목록 출력
글목록 출력
위 개념을 이용하여 웹 사이트 글목록 출력 과정을 유동적으로 바꿀 수 있다.
var list = '<ol>';
var i = 0;
while(i < filelist.length) {
list += `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
i++;
}
list += '</ol>';
먼저 <ol>태그를 위 형태로 바꾸고 원래 있던 위치에 ${list}를 넣는다.
if, else(모든 경우)에 대해서 위와 같이 바꿔주고 코드를 다음과 같이 수정하면 유동적으로 폴더 내부의 파일을 읽어들일 수 있다.
var http = require('http');
var fs = require('fs');
var url = require('url');
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 = '<ol>';
var i = 0;
while(i < filelist.length) {
list += `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
i++;
}
list += '</ol>';
var template = `
<!doctype html>
<html>
<head>
<title>WEB1 - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">WEB</a></h1>
${list}
<h2>${title}</h2>
<p>${description}</p>
</body>
</html>
`;
response.writeHead(200);
response.end(template);
})
} else {
fs.readdir('./data', function(error, filelist) {
var title = 'Welcome';
var description = 'Hello, Node.js';
var list = '<ol>';
var i = 0;
while(i < filelist.length) {
list += `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>`;
i++;
}
list += '</ol>';
fs.readFile(`data/${queryData.id}`, 'utf8', function(err, description) {
var title = queryData.id;
var template = `
<!doctype html>
<html>
<head>
<title>WEB1 - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">WEB</a></h1>
${list}
<h2>${title}</h2>
<p>${description}</p>
</body>
</html>
`;
response.writeHead(200);
response.end(template);
});
});
}
} else {
response.writeHead(404);
response.end('Not found')
}
});
app.listen(3000);
728x90
반응형