20강 반복문
console.log('A');
console.log('B');
var i = 0;
while(i < 2){
console.log('C1');
console.log('C2');
i = i + 1;
}
console.log('D');
21강 배열
var arr = ['A','B','C','D'];
console.log(arr[1]);
console.log(arr[3]);
arr[2] = 3;
console.log(arr);
console.log(arr.length);
arr.push('E');
console.log(arr);
22강 배열과 반복문
var number = [1,400,12,34];
var i = 0;
var total = 0;
while(i < number.length){
total = total + number[i];
i = i + 1;
}
console.log(`total : ${total}`);
23강 Nodejs - 파일 목록 알아내기
var testFolder = './data';
var fs = require('fs');
fs.readdir(testFolder, function(error, filelist){
console.log(filelist);
})
출력하면
data 안의 여러 파일 목록들이 출력되는데
출력형태는 ['A','B','C']배열이다.
코드 형태.
메소드( 매개변수, 함수(매개변수){ } )
24강 App제작 - 글목록 출력하기
배열과 글목록출력하기를 이용해서
글목록부분을 메소드readdir+배열을 이용했다
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 = '<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>';
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 = '<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>';
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);
'Backend > 생활코딩' 카테고리의 다른 글
[생활코딩 Node.js] 28강 동기와 비동기 (0) | 2021.02.15 |
---|---|
[생활코딩 Nodejs] 25강~27강 정리(함수로 코드 압축화하기) (0) | 2021.02.15 |
[생활코딩 Node.js] 14강~19강 정리 (Not found 조건 달기) (0) | 2021.02.09 |
[생활코딩 Node.js] 11강~13강 정리 (App 제작) (0) | 2021.02.08 |
[생활코딩 Node.js] 9강~10강 정리 (URL, Quarystring) (0) | 2021.02.07 |