-
Node.js 글 목록 출력(파일 목록 출력하기 참고)Node.js 2020. 8. 18. 22:32
리스트 변수에 filelist 배열의 정보 넣고
반복문과 ul태그를 통해 목록을 출력
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(err, filelist){ var title = 'Welcome'; var description = 'Hello Node.js'; var list = '<ul>'; var i = 0; while(i < filelist.length){ list += `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>` i += 1; } list = list + '</ul>' 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(err, filelist){ var title = 'Welcome'; var description = 'Hello Node.js'; var list = '<ul>'; var i = 0; while(i < filelist.length){ list += `<li><a href="/?id=${filelist[i]}">${filelist[i]}</a></li>` i += 1; } list = list + '</ul>' 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);
'Node.js' 카테고리의 다른 글
Node.js 동기와 비동기 / callback (0) 2020.08.19 Node.js 기초 최종 코드(생활코딩 따라하기) (0) 2020.08.19 Node.js 파일목록 알아내기(생활코딩 따라하기) (0) 2020.08.18 Node.js URL parse(URL 분석) (0) 2020.08.18 Node.js 파일 이용해서 본문 구현(생활코딩 따라하기) (0) 2020.08.18