분홍분홍 코딩 프로젝트
[Node.js] 기초실습편(1) 본문
url 사용~ 파일 읽기 코드
var http = require("http");
var fs = require("fs");
var url = require("url"); // nodejs에 url이라는 모듈을 사용하겠다
var app = http.createServer(function (request, response) {
var _url = request.url; // 입력된 url을 요청한다.
const queryData = url.parse(_url, true).query; // 입력된 url에서 query값을 이용한다.
let title = queryData.id;
if (_url == "/") {
title = "Welcome!";
}
if (_url == "/favicon.ico") {
response.writeHead(404);
response.end();
return;
}
fs.readFile(`data/${queryData.id}`, "utf8", (err, description) => {
const template = `
<!doctype html>
<html>
<head>
<title>WEB1 - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">Web</a></h1>
<ol>
<li><a href="/?id=HTML">HTML</a></li>
<li><a href="/?id=CSS">CSS</a></li>
<li><a href="/?id=JavaScript">JavaScript</a></li>
<li><a href="/?id=React">React</a></li>
</ol>
<h2>${title}</h2>
<p>${description}</p>
</body>
</html>
`;
response.end(template);
});
response.writeHead(200);
});
app.listen(3000);
require: 외부 모듈을 가져온다.
createServer: 웹 객체를 생성해주는 함수
request.url: query string의 정보
queryData: {변수명 : 값} 쌍들로 이루어진 객체. pathname, path 등의 url 정보가 들어가 있다.
- Url로 사용된 값 사용하기 (Query string)
query string 값은 ?{key}={value} 의 형태로 쓰기로 약속되어 있다.
이런 식으로 사용한다.
let title = queryData.id; // queryData가 가져온 url을 담은 변수이다.
- 특정 directrory 에서 파일을 읽기(+description 변수 생성은 덤)
fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
'/etc/passwd' 안에 나타낼 파일의 경로를 넣는다.
- 콘솔에서의 입력값
- 다른 경로로 들어왔을 때 Not found 구현
pathname : query string 이 없을 떄의 경로값. "/" or "/!@#!@$" 가 뜬다. ex) "/"
path : query string 이 있을 떄의 경로값 ex) "/?id=CSS"
+ if 활용
if(pathname이 "/" 일 떄) {
if(query string이 undefined 일 떄 )
[...]
} else {
[error 메시지]
}
전체코드
const http = require("http");
const fs = require("fs");
const url = require("url");
const app = http.createServer(function (request, response) {
const _url = request.url;
const queryData = url.parse(_url, true).query;
const pathname = url.parse(_url, true).pathname;
if (pathname === "/") {
if (queryData.id === undefined) {
fs.readFile(`data/${queryData.id}`, "utf8", (err, description) => {
const title = "Welcome to Node.js!";
description = "Let's leran Node.js!";
const template = `
<!doctype html>
<html>
<head>
<title>WEB1 - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">Web</a></h1>
<ol>
<li><a href="/?id=HTML">HTML</a></li>
<li><a href="/?id=CSS">CSS</a></li>
<li><a href="/?id=JavaScript">JavaScript</a></li>
<li><a href="/?id=React">React</a></li>
</ol>
<h2>${title}</h2>
<p>${description}</p>
</body>
</html>
`;
response.writeHead(200);
response.end(template);
});
} else {
fs.readFile(`data/${queryData.id}`, "utf8", (err, description) => {
console.log(description);
let title = queryData.id;
const template = `
<!doctype html>
<html>
<head>
<title>WEB1 - ${title}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="/">Web</a></h1>
<ol>
<li><a href="/?id=HTML">HTML</a></li>
<li><a href="/?id=CSS">CSS</a></li>
<li><a href="/?id=JavaScript">JavaScript</a></li>
<li><a href="/?id=React">React</a></li>
</ol>
<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);
문제
ol 태그를 ul 태그로 바꾸고 싶다. 이때 만약 바꿔야하는 ol태그가 수백 수천개라면?
고생스럽게도 일일이 바꿔줘야한다.
1. 특정 directory 내에 있는 파일의 리스트를 가져오기.
const testFolder = "./data"; // data directory 호출
const fs = require("fs");
fs.readdir(testFolder, (err, filelist) => {
console.log(filelist); // data directory 내 파일 리스트들을 불러온다.
});
2. 파일리스트 출력하기
파일리스트를 받아와 반복문으로 list를 동적으로 생성한다.
fs.readdir(dataFolder, (err, fileList) => {
const title = "Welcome to Node.js!";
const description = "Let's leran Node.js!";
let list = "<ol>";
for (let i = 0; i < fileList.length; i++) {
list =
list + `<li><a href="/?id=${fileList[i]}">${fileList[i]}</a></li>`;
}
list += "</ol>";
const 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>
`;
}
해결.
+함수를 이용해서 정리정돈하기
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) {
let list = "<ul>";
for (let i = 0; i < fileList.length; i++) {
list = list + `<li><a href="/?id=${fileList[i]}">${fileList[i]}</a></li>`;
}
list = list + "</ul>";
return list;
}
template 함수를 만들어 적절한 parameter들을 넣어준다.
끝.
이 다음부턴 동기,비동기, 콜백함수와 CRUD기능을 더 사용해서 꾸며볼 예정.
재밌네
'옛 포스트 > Node.js' 카테고리의 다른 글
[Node.js] 첫 만남 (0) | 2022.01.08 |
---|