Node.js
: Javascript를 브라우저가 아닌 외부에서 실행할 수 있게 만들어진 런타임 환경
Chrome의 V8엔진을 기반으로 실행된다.
다음과 같이 디렉터리 안에 js파일 문서를 만들고 cmd에서 해당 디렉터리로 이동한 다음에 node main.js와 같은 명령어로 웹 서버를 띄운다
localhost:3000포트에서 웹 서버가 띄워진다.
자바스크립트의 숫자 자료형을 다루는 방법
자바 스크립트의 문자열 자료형을 다루는 방법
중복을 제거하여 출력하기
문자열 리터럴이란?
: 런타임 시점에 일반 자바스크립트 문자열로 처리되어 내장된 표현식을 변환하는 형태이다.
http:
host :
port : 한 개의 컴퓨터 안에 여러개의 서버가 존재한다. 클라이언트가 접속할 때 연결되어 있는 서버에 접속해 인터페이스를
path : 어떤 디렉토리, 어떤 파일인지 나타냄
query string : 아이디의 value를 가져와 나타냄
id = HTML // Query String
nodejs url parse query string 하는 법
url.parse.query
모듈 : 노드 js의 수많은 기능을 비슷한 것끼리 grouping한것을 모듈이라고 한다.
var url = require('url');
'url이라는 노드는 url이라는 변수의 이름으로 사용할 것이다. '라는 뜻
동적 웹페이지 만들기
기존 html코드에서 URL에 따라 동적으로 변화하는 페이지를 만들고 싶다.
<!doctype html>
<html>
<head>
<title>WEB1 - HTML</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="index.html">WEB</a></h1>
<ol>
<li><a href="1.html">HTML</a></li>
<li><a href="2.html">CSS</a></li>
<li><a href="3.html">JavaScript</a></li>
</ol>
<h2>HTML</h2>
<p><a href="https://www.w3.org/TR/html5/" target="_blank" title="html5 speicification">Hypertext Markup Language (HTML)</a> is the standard markup language for <strong>creating <u>web</u> pages</strong> and web applications.Web browsers receive HTML documents from a web server or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.
<img src="coding.jpg" width="100%">
</p><p style="margin-top:45px;">HTML elements are the building blocks of HTML pages. With HTML constructs, images and other objects, such as interactive forms, may be embedded into the rendered page. It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. HTML elements are delineated by tags, written using angle brackets.
</p>
</body>
</html>
이 부분에서 query string에 따라 <h2>와 <title>부분을 바꿀 것이다.
querys string의 id값인 queryData.id 로 동적 바인딩을 진행한다.
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;
// 쿼리 문자열에서 매개변수를 얻기 위함
console.log(queryData.id);
if(_url == '/'){
_url = '/index.html';
}
if(_url == '/favicon.ico'){
return response.writeHead(404);
}
response.writeHead(200);
var template = `
<!doctype html>
<html>
<head>
<title>WEB1 - ${queryData.id}</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="index.html">WEB</a></h1>
<ol>
<li><a href="1.html">HTML</a></li>
<li><a href="2.html">CSS</a></li>
<li><a href="3.html">JavaScript</a></li>
</ol>
<h2>${queryData.id}</h2>
<p><a href="https://www.w3.org/TR/html5/" target="_blank" title="html5 speicification">Hypertext Markup Language (HTML)</a> is the standard markup language for <strong>creating <u>web</u> pages</strong> and web applications.Web browsers receive HTML documents from a web server or from local storage and render them into multimedia web pages. HTML describes the structure of a web page semantically and originally included cues for the appearance of the document.
<img src="coding.jpg" width="100%">
</p><p style="margin-top:45px;">HTML elements are the building blocks of HTML pages. With HTML constructs, images and other objects, such as interactive forms, may be embedded into the rendered page. It provides a means to create structured documents by denoting structural semantics for text such as headings, paragraphs, lists, links, quotes and other items. HTML elements are delineated by tags, written using angle brackets.
</p>
</body>
</html>`;
response.end(template);
});
app.listen(3000);
코드에 의해, id값으로 넣어준 문자열이 h2와 title값으로 바뀐다.
이렇게 이동하는 문서의 href 값을 ?id=HTML과 같이 바꾸어주어서 h2부분이 동적으로 바뀔 수 있게끔 한다.
이제 HTML, CSS, JavaScript 를 설명하는 모든 페이지의 html 문서를 만들 필요 없이 하나의 html문서의 일부 키워드만 바꿈으로써 동적으로 페이지를 구성할 수 있게 된다. 즉, 본문 부분의 데이터만 따로 추출해, 전체 페이지를 하나하나 구
성할 필요 없이 사용자의 요청에 해당하는 데이터만 화면에 뿌릴 수 있는 것이다.
파일 입출력
아무 글이나 넣은 sample.txt를 불러오는 js 코드를 작성해보자
var fs = require('fs');
fs.readFile('sample.txt', function(err,data) {
console.log(data);
});
실행이 안되는 이유는 node가 실행되는 실제 디렉토리와 위의 fileread.js의 디렉토리 위치가 달라서인데, 디렉토리를 바꾸는 명령어를 통해 fileread.js가 위치한 디렉터리로 이동한다.
> cd nodejs
> node fileread.js
제작 파일을 이용해 본문 구현
본문 p태그 부분을 data 디렉토리의 적당한 파일 문서의 내용으로 치환하려고 한다.
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 title = queryData.id;
console.log(queryData.id);
if(_url == '/'){
title = "Welcome"; // 첫 화면으로 가면 title(queryData.id)의 값을 Welcome으로 설
}
if(_url == '/favicon.ico'){
return response.writeHead(404);
}
response.writeHead(200);
fs.readFile(`data/${queryData.id}`, 'utf8',function(err, data){
var description = data;
var 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>
</ol>
<h2>${title}</h2>
<p>${description}</p>
</body>
</html>`;
response.end(template);
})
});
app.listen(3000);
입력한 id값에 따라 문서 내용이 치환되어 나타나진다.
자바스크립트 문법
Boolean datatype
console.log(true);
console.log(false);
a = 1; // a는 변수
// true = 1; ERROR! true는 boolean이므로 변수 명으로 사용할 수 없다.
Comparison operator
console.log(1+1);
// +는 이항 연산자
console.log(1==1); // true
// == 는 비교 연산자
console.log(1==2); // false
console.log(1 > 2); //false
console.log(1 < 2); // true
console. log (1===2); //true
name = 1; // 대입 연산자
Conditional statement
제어문의 대표적인 문법
console.log('A');
console.log('B');
// if(true){
// console.log('C1');
// }
// if(false){
// console.log('C2');
// }
if(true){
console.log('C1');
}
else{
console.log('C2');
}
console.log('D');
if문의 true의 위치를 바꾸게 함에 따라 굳이 C1,C2 두가지 케이스의 문서를 만들지 않고도 경우에 따라 다르게 출력할 수 있다.
그렇다면 입력값에 의해서 출력을 다르게 하려면?
입력값 : Parameter, Argument
How do I pass command line arguments to a Node.js program?
I have a web server written in Node.js and I would like to launch with a specific folder. I'm not sure how to access arguments in JavaScript. I'm running node like this: $ node server.js folder h...
stackoverflow.com
var args = process.argv.slice(2);
console.log(args);
console.log('A');
console.log('B');
if(true){
console.log('C1');
}
else{
console.log('C2');
}
console.log('D');
입력값이 egoing일때 node.js는 egoing이라는 output을 나오게 한다.
이것을 활용해, input값을 코드 내에서 활용할 수 있게 된다.
var args = process.argv;
console.log(args[2]);
console.log('A');
console.log('B');
if(args[2] === '1'){
console.log('C1');
}
else{
console.log('C2');
}
console.log('D');
코드를 다음과 같이 수정하고
이렇게 input값을 넣으면 args 리스트의 첫 항이 1이되어 ===이 성립하고
C1을 출력하는 if문이 true가 되어 C1이 출력된다.
주어진 id값에 따라 적절한 페이지를 불러내고, 지정하지 않은 id를 입력했을 때 Not Found가 뜨도록 해보자.
조건문을 사용해 구현
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 title = queryData.id;
var pathname = url.parse(_url, true).pathname;
if(pathname==='/') // path가 없는 코드로 접속
{
fs.readFile(`data/${queryData.id}`, 'utf8',function(err, data){
var description = data;
var 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>
</ol>
<h2>${title}</h2>
<p>${description}</p>
</body>
</html>`;
response.writeHead(200);
response.end(template);
})
}
else{
response.writeHead(404); // 200이라는 숫자는 파일을 성공적으로 접속했음을 알리게 되고, 404는 에러가 떴음을 알림
response.end('Not found');
}
});
app.listen(3000);
조건에 따라 다르게 만드는 application 만들기
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 title = queryData.id;
var pathname = url.parse(_url, true).pathname;
if(pathname==='/') // path가 없는 코드로 접속
{
//home으로 갔을 때
if(queryData.id === undefined){
fs.readFile(`data/${queryData.id}`, 'utf8',function(err, data){
var title = "Welcome";
var description = "Hello, Node.js";
var description = data;
var 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>
</ol>
<h2>${title}</h2>
<p>${description}</p>
</body>
</html>`;
response.writeHead(200);
response.end(template);
});
else{
fs.readFile(`data/${queryData.id}`, 'utf8',function(err, data){
var title = queryData.id
var description = data;
var 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>
</ol>
<h2>${title}</h2>
<p>${description}</p>
</body>
</html>`;
response.writeHead(200);
response.end(template);
});
}
}
fs.readFile(`data/${queryData.id}`, 'utf8',function(err, data){
var description = data;
var 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>
</ol>
<h2>${title}</h2>
<p>${description}</p>
</body>
</html>`;
response.writeHead(200);
response.end(template);
})
}
else{
response.writeHead(404); // 200이라는 숫자는 파일을 성공적으로 접속했음을 알리게 되고, 404는 에러가 떴음을 알림
response.end('Not found');
}
});
app.listen(3000);
반복문
요로코롬 쓰면 된다.
배열
array literal을 이용해 배열을 만들 수 있다.
배열과 반복문
노드 js 내에서 파일 디렉터리의 파일 리스트를 불러오는 법
: fs.readdir
이 output을 이용해 반복문 안에서 자동으로 글을 불러올 수 있다.
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==='/') // path가 없는 코드로 접속
{
//home으로 갔을 때
if(queryData.id === undefined){
fs.readdir('./data', function(error, filelist){
//filelist는 data디렉터리 안의 피일 이름들
// console.log(filelist);
var title = "Welcome";
var description = "Hello, Node.js";
/*
var list = ` <ul>
<li><a href="/?id=JavaScript">JavaScript</a></li>
<li><a href="/?id=HTML">HTML</a></li>
<li><a href="/?id=CSS">CSS</a></li>
</ul>`;
*/
var list = `<ul>`;
var i = 0;
while(i < filelist.length){ // filelist의 크기만큼 while문을 반복하며
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{ // id값이 있는 경우의 코드
fs.readdir('./data', function(error, filelist){
//filelist는 data디렉터리 안의 피일 이름들
// console.log(filelist);
var title = "Welcome";
var description = "Hello, Node.js";
// var description = data;
/*
var list = ` <ul>
<li><a href="/?id=JavaScript">JavaScript</a></li>
<li><a href="/?id=HTML">HTML</a></li>
<li><a href="/?id=CSS">CSS</a></li>
</ul>`;
*/
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 description = data;
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 { // path가 있는 곳으로 접속했을 때
response.writeHead(404); // 200이라는 숫자는 파일을 성공적으로 접속했음을 알리게 되고, 404는 에러가 떴음을 알림
response.end('Not found');
}
});
app.listen(3000);
Data 디렉터리에 파일을 추가하면
추가한 파일이 리스트에 표시되는 것을 확인할 수 있다. (반복문의 length가 +1 되고, filelist의 i값이 변화함에 따라 list변수에 ul태그 값이 추가되고 template변수, 즉 본문에 불러올 내용에서 title, list, description 등의 변수의 value가 달라지기 때문)
~ 24강까지 완료
'Framework > Node.js' 카테고리의 다른 글
인프런 노드 리액트 기초 강의 (Node JS, Express JS) 1~10강 (0) | 2021.07.30 |
---|---|
생활코딩 Node.js 25장-end (0) | 2021.07.22 |