3. “Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.”
“As an asynchronous event driven JavaScript runtime, Node is designed to build
scalable network applications.”
- nodejs.org
• 크롬의 V8 자바스크립트 엔진을 기반으로 만들어진 자바스크립트 런타임
• 네트워크 어플리케이션 제작을 위한 비동기 이벤트 기반 방식의 자바스크립트 런타임
What is Node.js?
4. “Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.”
“As an asynchronous event driven JavaScript runtime, Node is designed to build
scalable network applications.”
- nodejs.org
• 크롬의 V8 자바스크립트 엔진을 기반으로 만들어진 자바스크립트 런타임
• 네트워크 어플리케이션 제작을 위한 비동기 이벤트 기반 방식의 자바스크립트 런타임
= 서버사이드 자바스크립트 프레임워크
What is Node.js?
5. Feature
• Open Source
• Asynchronous & Event-driven
• Non-blocking I/O
• Single threaded
• Chrome’s V8 Engine
6. Open Source
“Permission is hereby granted, free of charge … without restriction, including without
limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software …”
- LICENSE of node.js
• 수정, 배포 등을 포함한 일체의 권리에 제한을 받지 않고 사용할 수 있는 오픈 소스
• https://github.com/nodejs/node
7. Asynchronous & Event-driven
• 절차 지향 프로그래밍 : 진입점에서부터 모든 동작이 차례대로 수행
• 이벤트 드리븐 : 입력 혹은 출력(event)이 발생함에 따라 동작이 처리(driven)
• 절차 지향 프로그래밍 방식은 동기적(Synchronous)으로 동작이 처리되는 반면, 이벤
트 드리븐 방식은 비동기적(Asynchronous)으로 동작이 처리됨
• 가장 기본적인 처리 방식으로 콜백(callback)이 존재
8. Non-blocking I/O
• Blocking : 어떠한 작업이 완료될 때 까지 다른 처리를 막는(blocking) 방식
• Non-blocking : 처리할 작업을 맡겨두고(non-blocking), 결과를 따로 처리하는 방식
• Sync/Asnyc의 개념과 혼동될 수 있으나, Blocking/Non-blocking을 처리하는 방식으
로 Sync/Async를 이용하게 된다.
9. Single threaded
• Tomcat, Apache : 사용자의 요청에 대해 thread를 생성해 처리
• Node.js : 단일 thread의 event loop 상에서 요청을 처리
• Context switching에 대한 비용 감소
• Multi-thread 환경에서 발생하는 요소 고려에 대한 부담 감소
15. Installation (Windows)
• Download on https://nodejs.org/en/download/
• ‘Windows Installer’
• ‘Next’혹은‘Install’,‘Finish’만 선택해 주면 설치 완료
16. Installation (Linux)
• Download on https://nodejs.org/en/download/
• ‘Source Code’
• GNU make를 위한 의존성 패키지 설치
• configure.sh를 통한 make 설정
• Make
• Install
17. Installation (Linux)
wget https://nodejs.org/dist/v4.4.3/node-v4.4.3.tar.gz
sudo apt-get update && apt-get upgrade
sudo apt-get install build-essential libssl-dev
tar -xzf node-v4.4.3.tar.gz
cd node-v4.4.3
./configure
make
sudo make install
18. Hello World
vim helloword.js // helloworld.js
console.log(“hello world!”)
node helloworld.js // execute
19. Hello World
vim helloword.js // helloworld.js
console.log(“hello world!”)
node helloworld.js // execute
20. Simple Server
vim simple_server.js // simple_server.js
var http = require('http')
http.createServer( (request, response) => {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end('<h1>Hello world!</h1>');
}).listen(3000)
console.log('Server running at http://localhost:3000');
node simple_server.js // execute (http://localhost:3000)
23. Simple Server
var http = require('http')
http.createServer( (request, response) => {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end('<h1>Hello world!</h1>');
}).listen(3000)
console.log('Server running at http://localhost:3000');
24. Simple Server
var http = require('http')
http.createServer( (request, response) => {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end('<h1>Hello world!</h1>');
}).listen(3000)
console.log('Server running at http://localhost:3000');
25. Simple Server
var http = require('http')
http.createServer( (request, response) => {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end('<h1>Hello world!</h1>');
}).listen(3000)
console.log('Server running at http://localhost:3000');
=> HTTP Module
26. HTTP Module
• HTTP 웹 서버와 관련된 기능을 담고있는 모듈
• HTTP Module은 다음과 같은 클래스를 포함
• 요청(Request)와 응답(Response)를 처리할 수 있는 Server
• 클라이언트의 요청에 대한 정보를 담는 IncomingMessage
• 서버의 처리 결과에 대한 정보를 담는 ServerResponse
• 다른 서버와의 통신 기능을 수행할 수 있는 ClientRequest
참고 : https://nodejs.org/api/http.html
27. • TCP/IP 기반으로 웹 상에서 정보를 주고받을 수 있는 프로토콜
• 클라이언트와 서버 사이에 이루어지는 요청/응답(request/response) 프로토콜
• OSI 7 Layer 중 Application Layer에 해당
• HTML 페이지를 전달하는데 주로 사용
HTTP
참고 : RFC 2616 (https://tools.ietf.org/html/rfc2616)
29. HTTP Message Structure
• HTTP 메시지는 크게 Request와 Response로 나뉘어짐
• 각 메시지는 Header와 Body로 구성
• Header는 커넥션 및 쿠키, 파일 종류 등 통신에 필요한 각종 정보를 서술
• Body는 실제 본문으로서 전송할 데이터를 서술
• 메시지 전문은 아래와 같이 구성
Request-Line | Status-Line
*(message-header CRLF)
CRLF
[ message-body ]
참고 : https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
35. Serving static files
var http = require('http')
var fs = require('fs') // ‘fs’ 모듈 로드
var server = http.createServer( (request, response) => {
fs.readFile('index.html', function(error, data) { // 파일 읽기
response.writeHead(200, {'Content-Type': 'text/html'}); // Header 작성
response.end(data); // 파일 전송
});
}).listen(3000);
console.log('Server running at http://localhost:3000');
36. Serving static files
var http = require('http')
…
// text/html 형식의 파일을 전송 할 것이라 명시
response.writeHead(200, {‘Content-Type’: ‘text/html’});
…
console.log('Server running at http://localhost:3000');
39. Web Page Presentation
• 사용자의 요청에 따라 HTML 페이지를 보여주기 위해서는?
var http = require('http')
var server = http.createServer( request, response => {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(‘<html>
<head><title>Hello world!</title></head>
<body>
<h1>Welcome to Node.js</h1>
<p>example page…</p>
</body>
</html>’);
}).listen(3000);
• 웹 페이지 소스를 하드 코딩으로 작성 == 번거롭다
40. Web Page Presentation
• 사용자의 요청에 따라 HTML 페이지를 보여주기 위해서는?
var http = require('http')
var server = http.createServer( request, response => {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(‘<html>
<head><title>Hello world!</title></head>
<body>
<h1>Welcome to Node.js</h1>
<p>example page…</p>
</body>
</html>’);
}).listen(3000);
• 웹 페이지 소스를 하드 코딩으로 작성 == 번거롭다
41. Web Page Presentation
• 사용자의 요청에 따라 HTML 페이지를 보여주기 위해서는?
var http = require('http')
var server = http.createServer( request, response => {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(‘<html>
<head><title>Hello world!</title></head>
<body>
<h1>Welcome to Node.js</h1>
<p>example page…</p>
</body>
</html>’);
}).listen(3000);
• 웹 페이지 소스를 하드 코딩으로 작성 == 번거롭다
42. Web Page Presentation
• 사용자의 요청에 따라 HTML 페이지를 보여주기 위해서는?
var http = require('http')
var server = http.createServer( request, response => {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(‘<html>
<head><title>Hello world!</title></head>
<body>
<h1>Welcome to Node.js</h1>
<p>example page…</p>
</body>
</html>’);
}).listen(3000);
• 웹 페이지 소스를 하드 코딩으로 작성 == 번거롭다
43. Web Page Presentation
• 사용자의 요청에 따라 HTML 페이지를 보여주기 위해서는?
var http = require('http')
var server = http.createServer( request, response => {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(‘<html>
<head><title>Hello world!</title></head>
<body>
<h1>Welcome to Node.js</h1>
<p>example page…</p>
</body>
</html>’);
}).listen(3000);
• 웹 페이지 소스를 하드 코딩으로 작성 == 번거롭다
44. Page Rendering
• Business Logic과 Presentation Logic을 구분하는 것이 기본 개념
• View를 EJS 문법(EJS) 및 HAML(Pug)에 따라 제작
• 만들어진 View는 Template Engine을 통해 렌더링
• Template Engine에는 Pug(Jade), EJS, Dust, Mustache 등이 존재
참고 : http://paularmstrong.github.io/node-templates
46. Syntax
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Pug</title>
<script type="text/javascript">
if (foo) bar(1 + 5)
</script>
</head>
<body>
<h1>Pug - node template engine</h1>
<div id="container" class="col">
<p>You are amazing</p>
<p>Pug is a terse and simple
templating language with a strong focus on
performance and powerful features.</p>
</div>
</body>
</html>
참고 : http://jade-lang.com
Pug
doctype html
html(lang="en")
head
title= pageTitle
script(type='text/javascript').
if (foo) bar(1 + 5)
body
h1 Pug - node template engine
#container.col
if youAreUsingPug
p You are amazing
else
p Get on it!
p.
Pug is a terse and simple templating
language with a strong focus on
performance and powerful features.
49. Simple Pug
var http = require('http');
var pug = require('pug');
var fs = require('fs');
http.createServer(function (request, response) {
fs.readFile('index.pug', 'utf8', function (error, data) {
var fn = pug.compile(data);
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(fn());
});
}).listen(3000);
console.log('Server running at http://localhost:3000');
참고 : http://jade-lang.com/api/
50. Simple Pug
var http = require('http');
var pug = require('pug'); // ‘pug’ 모듈 로드
var fs = require('fs');
http.createServer(function (request, response) {
fs.readFile('index.pug', 'utf8', function (error, data) {
var fn = pug.compile(data); // HTML 코드 제너레이터 생성
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(fn()); // 제너레이터를 이용해 응답
});
}).listen(3000);
console.log('Server running at http://localhost:3000');
참고 : http://jade-lang.com/api/
51. Simple Pug
var http = require('http');
var pug = require('pug'); // ‘pug’ 모듈 로드
var fs = require('fs');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(pug.renderFile('index.pug')); // 파일명을 이용한 코드 생성
}).listen(3000);
console.log('Server running at http://localhost:3000');
참고 : http://jade-lang.com/api/
56. Necessity of Database
• 특정 사람들만 글을 읽고 쓸 수 있는 게시판 제작
• 각 사람들에게 계정을 주고 권한을 부여
• 로그인 한 사용자들만 글을 쓰고 읽기가 가능
Q : 사용자 정보를 저장해 둘 곳?
57. Necessity of Database
• 특정 사람들만 글을 읽고 쓸 수 있는 게시판 제작
• 각 사람들에게 계정을 주고 권한을 부여
• 로그인 한 사용자들만 글을 쓰고 읽기가 가능
Q : 사용자 정보를 저장해 둘 곳?
A : Database
58. Database?
• 데이터 중복의 최소화
• 데이터의 무결성
• DBMS (DataBase Management System)
• 복수 사용자 관리
• 다수의 사용자에 의해 접근 = 동일한 데이터의 동시 사용 또는 변경
• 데이터의 일관성 보장 필요
• 허용된 권한을 통해서만 데이터로 접근 가능
• 복수의 연결 및 자원 관리
59. Language of Database
• SQL
• DB와 의사소통을 하기 위한 표준 언어
• DB 및 데이터의 읽기, 쓰기(생성), 수정, 삭제, 관리 등의 기능을 수행
• DDL (Data Definition Language)
• 데이터베이스의 구조 정의 또는 변경.
• DML (Data Manupulation Language)
• 데이터의 삽입, 삭제, 검색, 수정.
• DCL (Data Control Language)
• 데이터베이스에 대한 권한 제어.
64. Express
“Express is a minimal and flexible Node.js web application framework that provides a
robust set of features for web and mobile applications.”
- expressjs.com
• Express : Node.js를 기반으로 한 가볍고 유연한 Web Application Framework
• Main features
• Routing
• Managing middlewares
• Serving static files
참고 : Express (http://expressjs.com)
65. Express & Connect
• ‘Connect’는 미들웨어(Middleware)를 기반으로 Node.js의 HTTP 서버 기능을 확장
해 주는 모듈 (extensible HTTP server framework for node using "plugins" known
as middleware)
• 초기‘Express’는 Connect를 기반으로 설계
• 이로 인해 여러 문제가 발생 (Connect에 대한 의존성, 성능 이슈 등)
• 위의 문제를 해결하기 위해 Express 4.0 버전부터 의존성을 제거하고 독자적인
Router를 가지게 됨
참고 : Express GitHub (https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x)
66. Routing?
• 클라이언트가 요청한 각각의 경로(URL)에 대한 처리는 어떻게 할까
• http://localhost:3000/
• http://localhost:3000/hello
• http://localhost:3000/world
• ….
67. Routing?
• 클라이언트가 요청한 각각의 경로(URL)에 대한 처리는 어떻게 할까
• http://localhost:3000/
• http://localhost:3000/hello
• http://localhost:3000/world
• ….
=> 마지막 컴포넌트(/, /hello, /world)를 구하고, 각각에 대한 로직을 구성
70. Routing
• if-else / switch-case 문을 이용한 분기 처리는 분기가 많아질수록 비효율적
• 또한 자칫 스파게티 코드가 되기 쉬움
• Routing 기능만을 독립적으로 수행하고, 로직을 주입할 수 있도록 하자
71. Routing
• if-else / switch-case 문을 이용한 분기 처리는 분기가 많아질수록 비효율적
• 또한 자칫 스파게티 코드가 되기 쉬움
• Routing 기능만을 독립적으로 수행하고, 로직을 주입할 수 있도록 하자
=> Router (라우터)
72. Routing on Express
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
}).post('/', function (req, res) {
res.send('Got a POST request');
}).put('/user', function (req, res) {
res.send('Got a PUT request at /user');
}).delete('/user', function (req, res) {
res.send('Got a DELETE request at /user');
}).listen(3000, function () {
console.log('Example app listening on port 3000!');
});
73. Routing on Express
var express = require('express'); // express 모듈 로드
var app = express();
app.get('/', function (req, res) { // ‘/’의 GET 메서드에 대한 분기
res.send('Hello World!');
}).post('/', function (req, res) { // ‘/’의 POS 메서드에 대한 분기
res.send('Got a POST request');
}).put('/user', function (req, res) { // ‘/’의 PUT 메서드에 대한 분기
res.send('Got a PUT request at /user');
}).delete('/user', function (req, res) { // ‘/’의 DELETE 메서드에 대한 분기
res.send('Got a DELETE request at /user');
}).listen(3000, function () {
console.log('Example app listening on port 3000!');
});
74. Page Rendering
// app.js
var express = require('express');
var app = express();
app.set('view engine', ‘jade');
app.get('/', function (req, res) {
// View engine을 이용해 Page rendering
res.render('index', { title: 'Hey', message: 'Hello there!'});
}).listen(3000, function () {
console.log('Server running at http://localhost:3000');
});
// index.jade
html
head
title!= title
body
h1!= message
75. Page Rendering
// app.js
var express = require('express');
var app = express();
app.set('view engine', ‘jade'); // jade 엔진을 사용하도록 설정
app.get('/', function (req, res) {
// View engine을 이용해 Page rendering
res.render('index', { title: 'Hey', message: 'Hello there!'});
}).listen(3000, function () {
console.log('Server running at http://localhost:3000');
});
// index.jade
html
head
title!= title
body
h1!= message