SlideShare a Scribd company logo
Geun-Hyung Kim
UMCL @ Dong-Eui University
Introduction to
Node.js
개 요
Node.js ?
Server-side framework
useful for building highly scalable and fast
network applications
JavaScript runtime built on Chrome’s V8 JavaScript engine.
It uses an event-driven, non-blocking I/O model that makes
it lightweight and efficient, perfect for data-intensive real-
time applications that run across distributed devices
developed by Ryan Dahl in 2009
개 요
Architecture
node standard library
node bindings
(socket, http, etc.)
V8
thread
pool
(libeio)
event
loop
(libev)
DNS
(c-ares)
crypto
(OpenSSL)
JavaScript C/C++
개 요
Brief History
JavaScript’s Speed revolution has started since 2008.
2008. 9: Google releases Chrome Web browser beta version based on
V8 JavaScript Engine
2009. 1: ServerJS project (currentCommonJS project) started to use
JavaScript in other areas except Web browser.
2009. 11: Node.js was released based on CommonJS standard and V8
JavaScript Engine (for Linux)
2011. 5: npm (Node Package Manager) 1.0 was released
2011. 7: Node.js for Windows was released
2009. 3: Node.js had a name.
개 요
Why Node.js?
<source: modulecounts.com>
Node packages are growing faster
than Ruby, Python, and Java
combined
asynchronous, event-driven
framework
designed for creating scalable
network app.
single-threaded
uses a concurrency model based on
an event loop
non-blocking with callback function:
handle concurrent operations
without multiple thread of execution
no buffering
ideal for I/O bound applications,
but not so great for CPU-heavy
applications
개 요
Event based Asynchronous
<현황>
각 상점에 가서 물건을 구매하기 위해서 대기를 기다려야 함.
한 상점 씩 다니면서 물건을 살 경우 27분이 소요된다.
Event based Asynchronous
<해결책>
1. 몸을 복제하여 동시에 여러 가게에 간다. (thread 기반 동기방식)
2. 각 상점에서 대기표를 나누어주는 시스템을 바꾸고 대기표를 받고 기다린다.
(이벤트 기반 비동기 방식)
Sync. vs. Async. I/O
fileRead(fileName)
1. 파일 읽기 요청
3. 파일 읽기 완료
2. 파일 읽는 중
Synchronous I/O
Sync. vs Async I/O
fileRead(fileName,callback)
1. 파일 읽기 요청
4. 파일 읽기 종료 후
callback 함수 호출
3. 파일 읽는 중
2. 바로 리턴
Asynchronous I/O
Installing Node.js
Installation
Official Node.js website
https://nodejs.org/en/download/
windows installer 다운로드하여 설치
Installation
Version Check and Start!
1. version check
2. execute node (it shows Node shell.)
3. type simple code to prompt “Hello World” to the console
Node shell 에서 빠져 나오는 방법: Ctrl+d
Node Program
Hello World!
// helloworld.js
console.log(“Hello World”);
// execute helloworld.js
$ node helloworld.js
Server Programming
HTTP Server
Target
로그인
id:
pw:
login
geunkim Welcome to this world
To geunkim
http://localhost:8000/start http://localhost:8000/hello
HTTP Server
var http = require(“http”);
http.createServer(function (request, response) {
response.writeHead(200, {“Content-Type”:”text/plain”});
response.write(“Hello World!”);
response.end();
}).listen(8000);
console.log(“Http Server has been started”);
// server.js
// cmd terminal
$ node server.js
// browser
http://localhost:8000
Simple HTTP Server - 1
HTTP Server
var http = require(“http”);
function onRequest(request, response) {
console.log(“Request Received”);
response.writeHead(200, {“Content-Type”:”text/plain”});
response.write(“Hello World!”);
response.end();
}
http.createServer(onRequest).listen(8000);
console.log(“Http Server has been started”);
// server1.js
Simple HTTP Server - 2
Node.js has a simple module loading system.
module: a single unit of code which encapsulates
related codes into.
When creating a module, this can be interpreted as
moving all related functions into a file.
In Node.js, files and modules are in one-to-one
correspondence (한 파일이 모듈이 하나..).
Assign an expression in a module file, that we want to
become available in other files to the exports object.
making a user module
Module
<ref: https://nodejs.org/api/modules.html#modules_modules>
making a user module
Exporting a Module
exports.sayHelloInEnglish = function() {return “HELLO”;};
exports.sayHelloInSpanish = function() {return “Hola”;};
// greetings.js
exports.add = function(a, b) {return a+b;};
exports.sub = function(a, b) {return a-b;};
exports.mul = function(a, b) {return a*b;};
exports.div = function(a, b) {return a/b;};
// calc.js
// circle.js
const PI = Math.PI;
exports.area = (r) => PI *r *r;
exports.circumference = (r) => 2 *PI * r;
<ref: https://nodejs.org/api/modules.html#modules_modules>
<ref: https://www.sitepoint.com/understanding-module-exports-exports-node-js/>
(info.) The keyword require is used in Node.js to import modules.
make a user module
Import a Module
var require = function(path){
// …
return module.exports;
}
require module files in your js file.
var greetings = require(“./greetings.js”);
access the publicly available methods of greetings.js
greetings.sayHelloInEnglish();
greetings.sayHelloInSpanish();
<ref: https://www.sitepoint.com/understanding-module-exports-exports-node-js/ >
import calc.js
making a user module
Import a Module
import circle.js
var calcObj = require(“./calc.js”);
var circle = require(“./circle.js”);
When a file is run directly from Node.js, require.main is
set to its module.
So, developer can determine if a file has been run directly by testing
For a file foo.js,
this will be true when it run via node foo.js.
But, this will be false, then it run by require(“./foo”)
making a user module
Accessing the main module
<ref: https://nodejs.org/api/modules.html#modules_modules>
require.main === module
making a user module
http server module
var http = require(“http”);
function start() {
function onRequest(request, response) {
console.log(“Request Received”);
response.writeHead(200, {“Content-Type”:”text/plain”});
response.write(“<h1>Welcome to HTTP Server !</h1>”);
response.write(“<h2>Hello World..</h2>”);
response.end();
}
http.createServer(onRequest).listen(8000);
console.log(“Http Server has been started”);
}
exports.start = start;
// httpServer.js (version 1)
making a user module
using http server module
var httpServer = require(“./httpServer”);
httpServer.start();
// index.js (version 1)
// execute index.js
$ node index.js
// browser
index.js
httpServer
start()
Http Server는 다양한 사용자 요청에 응답해야 함
조회를 위한 요청, 저장을 위한 요청 등 다양한 요청을 식별하는 routing
기능을 고려
Router
request URL과 GET/POST parameter에 따라 실행할 코드를 결정
Routing: Dependency Injection
Dependency Injection
HTTP 요청에서 URL과 GET/POST Parameter의 추출이 필요
이 정보는 어디에 있을까 ?
Routing: url parsing
url and query parsing
http://localhost:8000/start?foo=bar&hello=world
url.parse(string).pathname
querystring.parse(string)[“foo”]
url.parse(string).query
querystring.parse(string)[“hello”]
request.url
require “url” module
require “querystring” module
Routing: url parsing
http://localhost:8000/start?foo=bar&hello=world
parsing results:
url and query parsing
Routing: url parsing
request url
var http = require(“http”);
var url = require(“url”);
function onRequest(request, response) {
console.log(request.url);
response.writeHead(200, {“Content-Type”:”text/plain”});
response.write(“Hello World!”);
response.end();
}
http.createServer(onRequest).listen(8000);
console.log(“Http Server has been started”);
// httpServer.js (version 1-1)
Routing: pathname parsing
pathname parsing
var http = require(“http”);
var url = require(“url”);
function start() {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log(“Request for ” + pathname + “ received.”);
response.writeHead(200, {“Content-Type”:”text/plain”});
response.write(“<h1>Welcome to HTTP Server !<h1>”);
response.write(“<h2>Hello World..<h2>”);
response.end();
}
http.createServer(onRequest).listen(8000);
console.log(“Http Server has been started”);
}
exports.start = start;
//httpServer.js (version 2)
Routing: router module
simple router
function route(pathName) {
console.log(“about to route a request for “ + pathName);
}
exports.route = route;
// router.js (version 1)
index.js
httpServer
start()
router
route()inject function
index.js에서 router module을 로딩하고 route()함수를 httpServer에 전달하여 실행하는 구조
Dependency Injection
server 코드 변경없이 router 함수 교체가 가능
Routing: router
var httpServer = require(“./httpserver”);
var router = require(“./router”);
httpServer.start(router.route);
// index.js (version 2)
index.js with router
server.js 는 start() 실행 시 route 함수를 전달하여
‘request’ 이벤트가 발생할 때 마다 route() 함수를 호출하여
클라이언트 요청을 식별
Routing: router
var http = require(“http”);
var url = require(“url”);
function start(route) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log(“Request for ” + pathname + “ received.”);
route(pathname); // injected function call
response.writeHead(200, {“Content-Type”:”text/plain”});
response.write(“<h2>Hello World..<h2>”);
response.end();
}
http.createServer(onRequest).listen(8000);
console.log(“Http Server has been started”);
}
exports.start = start;
//httpServer.js (version 3)
httpServer with router
Server: receives client’s request
Router: route the client’s request to the request handler
Request Handler: process the client’s specific request
Routing: Request Handler
Request Handler
index.js
httpServer
start()
router
route()
inject function
request
Handler
handle
Routing: Request Handler
Request Handler
//requestHandlers.js (version 0)
function start() {
console.log(“Request handler ‘start’ was called”);
return “Welcome Start Page”;
}
function hello() {
console.log(“Request handler ‘hello’ was called”);
return “Welcome Hello Page”;
}
exports.start = start; //export start
exports.hello = hello;
Routing: Request Handler
Request Handler
//requestHandlers.js (version 1)
function start() {
console.log(“Request handler ‘start’ was called”);
return “Welcome Start Page”;
}
function hello() {
console.log(“Request handler ‘hello’ was called”);
return “Welcome Hello Page”;
}
var handle = {};
handle[“/“] = start;
handle[“/start”] = start;
handle[“/hello”] = hello;
exports.handle = handle; //export JavaScript Object
Routing: Request Handler
index.js with request handler
var httpServer = require(“./httpserver”);
var router = require(“./router”);
var requestHandlers = require(“./requestHandlers”);
httpServer.start(router.route, requestHandlers.handle);
// index.js (version 3)
start() 실행 시 route 함수와 handler 객체를 전달하고
‘request’ 이벤트가 발생할 때 마다
handler 객체를 route() 함수에 전달하여 호출하여
클라이언트의 요청을 식별하고 해당 기능 수행
Routing: Request Handler
router.js with request handler
function route(handle, pathName) {
console.log(“about to route a request for “ + pathName);
if (typeof handle[pathName] === ‘function’) {
return handle[pathName]();
} else {
console.log(“No request handler found for “ + pathName);
return “404 Not Found”;
}
}
exports.route = route;
// router.js (version 2)
요청(pathName) 별로 다른 함수를 호출
Routing: Request Handler
//httpServer.js (version 4)
httpServer with router
var http = require(“http”);
var url = require(“url”);
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log(“Request for ” + pathname + “ received.”);
var content = route(handle, pathname);
response.writeHead(200, {“Content-Type”:”text/plain”});
response.write(content);
response.end();
}
http.createServer(onRequest).listen(8000);
console.log(“Http Server has been started”);
}
exports.start = start;
construct response message with return value
of request handler
Routing: Blocking
From request to response
HTTP Server
Router
Request Handlers
request
url forwarding
invoke handler
response
return result
return result
Problem:
Request Handler’s processing time may degrade the performance of HTTP Server.
Routing: Blocking
Performance
//requestHandlers.js (version 1-1)
function start() {
console.log(“Request handler ‘start’ was called”);
function sleep(msecs) {
var startTime = new Date().getTime();
while(new Date().getTime() < startTime + msecs);
}
sleep(10000); // 10 sec waiting
return “Welcome Start Page”;
}
Server waits util this function returns.
This makes the response delay of other request.
Routing: Non Blocking
From request to response
HTTP Server
Router
Request Handlers
request
pass response object
pass response object
response
Each request handler sends the response message individually.
Routing: Non Blocking
httpServer with non-blocking
//httpServer.js (version 5)
var http = require(“http”);
var url = require(“url”);
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log(“Request for ” + pathname + “ received.”);
route(handle, pathname, response);
}
http.createServer(onRequest).listen(8000);
console.log(“Http Server has been started”);
}
exports.start = start;
function route(handle, pathName, response) {
console.log(“about to route a request for “ + pathName);
if (typeof handle[pathName] === ‘function’) {
handle[pathName](response);
} else {
console.log(“No request handler found for “ + pathName);
response.writeHead(404, {“Content-Type”:”text/plain”});
response.write(“404 Not Found”);
response.end();
}
}
exports.route = route;
// router.js (version 3)
Non blocking router
View Logic
View logic for POST
//start function in requestHandlers.js (version 2)
function start(response) {
console.log(“Request handler ‘start’ was called”);
var body = “<html><head><title>First View</title>”+
“<meta charset=‘UTF-8’></head><body>“ +
“로그인</br>”+
“<form action=‘/hello’ method=‘post’>” +
“id: <input type=‘text’ name=‘id’></input>”+
“ <input type=‘submit’ value=‘login’/></br>”+
“pw: <input type=‘text’ name=‘pw’></input>”+
“</form></body></html>”;
response.writeHead(200, {“Content-Type”:”text/html”});
response.write(body);
response.end();
}
POST data receiving
Asynchronous Data receiving
request.addListener(“data”, function(chunk) {
// called when a new chunk of data was received
}
request.addListener(“end”, function() {
// called when all chunks of data has been received
}
POST data receiving
httpServer with POST
function onRequest(request, response) {
var postData =“”;
var pathname = url.parse(request.url).pathname;
console.log(“Request for ” + pathname + “ received.”);
request.setEncoding(“utf8”);
request.addListener(“data”, function(chunk) {
postData += chunk;
});
request.addListener(“end”, function() {
route(handle, pathname, response, postData);
});
}
//onRequest function in httpServer.js (version 6)
POST data receiving
function route(handle, pathName, response, postData) {
console.log(“about to route a request for “ + pathName);
if (typeof handle[pathName] === ‘function’) {
handle[pathName](response, postData);
} else {
console.log(“No request handler found for “ + pathName);
response.writeHead(404, {“Content-Type”:”text/plain”});
response.write(“404 Not Found”);
response.end();
}
}
exports.route = route;
Router with POST
// router.js (version 4)
Pass POST data to the Client
Request handler with POST
function hello(response, postData) {
console.log(“Request handler ‘hello’ was called”);
var out = “To “ + querystring.parse(postData)[“id”];
response.writeHead(200, {“Content-Type”:”text/plain”});
response.write(out);
response.write(“</br> Welcome to this World”);
response.end();
}
//requestHandlers.js (version 3)
GET data receiving
httpServer with GET
function onRequest(request, response) {
var getData =“”;
var pathname = url.parse(request.url).pathname;
console.log(“Request for ” + pathname + “ received.”);
getData += url.parse(request.url).query;
route(handle, pathname, response, getData);
}
//onRequest function in httpServer.js (version 7)
GET data receiving
function route(handle, pathName, response, getData) {
console.log(“about to route a request for “ + pathName);
if (typeof handle[pathName] === ‘function’) {
handle[pathName](response, getData);
} else {
console.log(“No request handler found for “ + pathName);
response.writeHead(404, {“Content-Type”:”text/plain”});
response.write(“404 Not Found”);
response.end();
}
}
exports.route = route;
Router with GET
// router.js (version 4)
View Logic
View logic for GET
//start function in requestHandlers.js (version 3)
function start(response) {
console.log(“Request handler ‘start’ was called”);
var body = “<html><head><title>First View</title>”+
“<meta charset=‘UTF-8’></head><body>“ +
“로그인</br>”+
“<form action=‘/hello’ method=‘get’>” +
“id: <input type=‘text’ name=‘id’></input>”+
“ <input type=‘submit’ value=‘login’></br>”+
“pw: <input type=‘text’ name=‘pw’></input>”+
“</form></body></html>”;
response.writeHead(200, {“Content-Type”:”text/html”});
response.write(body);
response.end();
}
Pass GET data to the Client
Request handler with GET
function hello(response, getData) {
console.log(“Request handler ‘hello’ was called”);
var out = “To “ + querystring.parse(getData)[“id”];
response.writeHead(200, {“Content-Type”:”text/plain”});
response.write(out);
response.write(“</br> Welcome to this World”);
response.end();
}
//requestHandlers.js (version 4)
Node: Appendix
Who uses Node ?
E-Commerce
Payment Processing
Social Media
Realtime Services
Media Applications
Enterprise Services
Node: Appendix
Apps suited for Node.js
Node.js: Hello로 시작하는 Web 애플리케이션
http://www.nextree.co.kr/p8574/
The Node Beginner Book
Simona Clapan, “The MEAN stack - SoCalCodeCamp -
june 29th 2014” from slidehsare
References

More Related Content

KEY
Git and GitHub
PDF
Docker d2 박승환
PDF
Git and github - Verson Control for the Modern Developer
PPTX
PDF
Git and Github
PDF
Git Introduction Tutorial
PDF
Collaborative development with Git | Workshop
PDF
Mini git tutorial
Git and GitHub
Docker d2 박승환
Git and github - Verson Control for the Modern Developer
Git and Github
Git Introduction Tutorial
Collaborative development with Git | Workshop
Mini git tutorial

What's hot (20)

PDF
Git & GitHub for Beginners
PDF
Deep dark-side of git: How git works internally
PPTX
Git One Day Training Notes
PPTX
Introduction to Git / Github
PDF
Git: An introduction of plumbing and porcelain commands
PDF
Docker workshop 0507 Taichung
PDF
Advanced Git Tutorial
PPT
Git training
PDF
Git Tutorial
PPTX
Git tutorial
DOCX
setting up a repository using GIT
PPTX
Git learn from scratch
PDF
Inside GitHub with Chris Wanstrath
PDF
Github - Git Training Slides: Foundations
PPTX
Introduction git
PDF
手把手帶你學Docker 03042017
PDF
Intro to Git and GitHub
PDF
Git basics for beginners
PDF
Git Version Control System
PDF
Git Tutorial I
Git & GitHub for Beginners
Deep dark-side of git: How git works internally
Git One Day Training Notes
Introduction to Git / Github
Git: An introduction of plumbing and porcelain commands
Docker workshop 0507 Taichung
Advanced Git Tutorial
Git training
Git Tutorial
Git tutorial
setting up a repository using GIT
Git learn from scratch
Inside GitHub with Chris Wanstrath
Github - Git Training Slides: Foundations
Introduction git
手把手帶你學Docker 03042017
Intro to Git and GitHub
Git basics for beginners
Git Version Control System
Git Tutorial I
Ad

Viewers also liked (15)

PDF
COMO CREAR UN TEXTO
PDF
by the numbers
PPTX
Sistemas operativos
PPT
Renting OCNJ
PPTX
салмина алина 1921_информатика
PPTX
Perdiqua
PDF
Riler v California (REAL)
PDF
Mec�nica dos fluidos
PPT
Tree and Binary Search tree
PPTX
Maslow's Needs
PDF
Objectives of ncert asw pdf
PPT
Queue in Data Structure
ODP
Els paisatges agraris (estela gil 3re) (2)
PPTX
Ebola
PPTX
Alzheimer
COMO CREAR UN TEXTO
by the numbers
Sistemas operativos
Renting OCNJ
салмина алина 1921_информатика
Perdiqua
Riler v California (REAL)
Mec�nica dos fluidos
Tree and Binary Search tree
Maslow's Needs
Objectives of ncert asw pdf
Queue in Data Structure
Els paisatges agraris (estela gil 3re) (2)
Ebola
Alzheimer
Ad

Similar to 5.node js (20)

PPT
Introducing to node.js
PDF
Node.js Jaram Winter Workshop 2014
PDF
Node.js 시작하기
PDF
What is nodejs
PDF
Nodejs 프로그래밍 ch.3
PPT
Asynchronous architecture (Node.js & Vert.x)
PPTX
A complete guide to Node.js
KEY
Nodejs web,db,hosting
PDF
[212] large scale backend service develpment
PDF
Introduction to Node js for beginners + game project
PDF
PPTX
Nodejs web service for starters
PPTX
Introduction to Node (15th May 2017)
PDF
540slidesofnodejsbackendhopeitworkforu.pdf
DOCX
Node js getting started
PDF
Jaap : node, npm & grunt
PPTX
Introducing Node.js in an Oracle technology environment (including hands-on)
KEY
Writing robust Node.js applications
PPTX
Introduction to node
Introducing to node.js
Node.js Jaram Winter Workshop 2014
Node.js 시작하기
What is nodejs
Nodejs 프로그래밍 ch.3
Asynchronous architecture (Node.js & Vert.x)
A complete guide to Node.js
Nodejs web,db,hosting
[212] large scale backend service develpment
Introduction to Node js for beginners + game project
Nodejs web service for starters
Introduction to Node (15th May 2017)
540slidesofnodejsbackendhopeitworkforu.pdf
Node js getting started
Jaap : node, npm & grunt
Introducing Node.js in an Oracle technology environment (including hands-on)
Writing robust Node.js applications
Introduction to node

More from Geunhyung Kim (7)

PDF
7. sorting
PDF
6. binary tree
PDF
5. queue
PDF
4. stack
PDF
1. introduction to algorithm
PDF
11. git basic
PDF
3. linked list
7. sorting
6. binary tree
5. queue
4. stack
1. introduction to algorithm
11. git basic
3. linked list

Recently uploaded (20)

PDF
top salesforce developer skills in 2025.pdf
PPT
Introduction Database Management System for Course Database
PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
L1 - Introduction to python Backend.pptx
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
medical staffing services at VALiNTRY
PDF
Best Practices for Rolling Out Competency Management Software.pdf
PDF
AI in Product Development-omnex systems
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Introduction to Artificial Intelligence
PPTX
Online Work Permit System for Fast Permit Processing
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
ISO 45001 Occupational Health and Safety Management System
PPTX
AIRLINE PRICE API | FLIGHT API COST |
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Presentation of Computer CLASS 2 .pptx
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
top salesforce developer skills in 2025.pdf
Introduction Database Management System for Course Database
The Role of Automation and AI in EHS Management for Data Centers.pdf
Odoo POS Development Services by CandidRoot Solutions
L1 - Introduction to python Backend.pptx
How to Choose the Right IT Partner for Your Business in Malaysia
medical staffing services at VALiNTRY
Best Practices for Rolling Out Competency Management Software.pdf
AI in Product Development-omnex systems
Understanding Forklifts - TECH EHS Solution
Introduction to Artificial Intelligence
Online Work Permit System for Fast Permit Processing
How to Migrate SBCGlobal Email to Yahoo Easily
ISO 45001 Occupational Health and Safety Management System
AIRLINE PRICE API | FLIGHT API COST |
Softaken Excel to vCard Converter Software.pdf
Presentation of Computer CLASS 2 .pptx
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus

5.node js

  • 1. Geun-Hyung Kim UMCL @ Dong-Eui University Introduction to Node.js
  • 2. 개 요 Node.js ? Server-side framework useful for building highly scalable and fast network applications JavaScript runtime built on Chrome’s V8 JavaScript engine. It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real- time applications that run across distributed devices developed by Ryan Dahl in 2009
  • 3. 개 요 Architecture node standard library node bindings (socket, http, etc.) V8 thread pool (libeio) event loop (libev) DNS (c-ares) crypto (OpenSSL) JavaScript C/C++
  • 4. 개 요 Brief History JavaScript’s Speed revolution has started since 2008. 2008. 9: Google releases Chrome Web browser beta version based on V8 JavaScript Engine 2009. 1: ServerJS project (currentCommonJS project) started to use JavaScript in other areas except Web browser. 2009. 11: Node.js was released based on CommonJS standard and V8 JavaScript Engine (for Linux) 2011. 5: npm (Node Package Manager) 1.0 was released 2011. 7: Node.js for Windows was released 2009. 3: Node.js had a name.
  • 5. 개 요 Why Node.js? <source: modulecounts.com> Node packages are growing faster than Ruby, Python, and Java combined asynchronous, event-driven framework designed for creating scalable network app. single-threaded uses a concurrency model based on an event loop non-blocking with callback function: handle concurrent operations without multiple thread of execution no buffering ideal for I/O bound applications, but not so great for CPU-heavy applications
  • 6. 개 요 Event based Asynchronous <현황> 각 상점에 가서 물건을 구매하기 위해서 대기를 기다려야 함. 한 상점 씩 다니면서 물건을 살 경우 27분이 소요된다.
  • 7. Event based Asynchronous <해결책> 1. 몸을 복제하여 동시에 여러 가게에 간다. (thread 기반 동기방식) 2. 각 상점에서 대기표를 나누어주는 시스템을 바꾸고 대기표를 받고 기다린다. (이벤트 기반 비동기 방식)
  • 8. Sync. vs. Async. I/O fileRead(fileName) 1. 파일 읽기 요청 3. 파일 읽기 완료 2. 파일 읽는 중 Synchronous I/O
  • 9. Sync. vs Async I/O fileRead(fileName,callback) 1. 파일 읽기 요청 4. 파일 읽기 종료 후 callback 함수 호출 3. 파일 읽는 중 2. 바로 리턴 Asynchronous I/O
  • 12. Installation Version Check and Start! 1. version check 2. execute node (it shows Node shell.) 3. type simple code to prompt “Hello World” to the console Node shell 에서 빠져 나오는 방법: Ctrl+d
  • 13. Node Program Hello World! // helloworld.js console.log(“Hello World”); // execute helloworld.js $ node helloworld.js
  • 15. HTTP Server Target 로그인 id: pw: login geunkim Welcome to this world To geunkim http://localhost:8000/start http://localhost:8000/hello
  • 16. HTTP Server var http = require(“http”); http.createServer(function (request, response) { response.writeHead(200, {“Content-Type”:”text/plain”}); response.write(“Hello World!”); response.end(); }).listen(8000); console.log(“Http Server has been started”); // server.js // cmd terminal $ node server.js // browser http://localhost:8000 Simple HTTP Server - 1
  • 17. HTTP Server var http = require(“http”); function onRequest(request, response) { console.log(“Request Received”); response.writeHead(200, {“Content-Type”:”text/plain”}); response.write(“Hello World!”); response.end(); } http.createServer(onRequest).listen(8000); console.log(“Http Server has been started”); // server1.js Simple HTTP Server - 2
  • 18. Node.js has a simple module loading system. module: a single unit of code which encapsulates related codes into. When creating a module, this can be interpreted as moving all related functions into a file. In Node.js, files and modules are in one-to-one correspondence (한 파일이 모듈이 하나..). Assign an expression in a module file, that we want to become available in other files to the exports object. making a user module Module <ref: https://nodejs.org/api/modules.html#modules_modules>
  • 19. making a user module Exporting a Module exports.sayHelloInEnglish = function() {return “HELLO”;}; exports.sayHelloInSpanish = function() {return “Hola”;}; // greetings.js exports.add = function(a, b) {return a+b;}; exports.sub = function(a, b) {return a-b;}; exports.mul = function(a, b) {return a*b;}; exports.div = function(a, b) {return a/b;}; // calc.js // circle.js const PI = Math.PI; exports.area = (r) => PI *r *r; exports.circumference = (r) => 2 *PI * r; <ref: https://nodejs.org/api/modules.html#modules_modules> <ref: https://www.sitepoint.com/understanding-module-exports-exports-node-js/>
  • 20. (info.) The keyword require is used in Node.js to import modules. make a user module Import a Module var require = function(path){ // … return module.exports; } require module files in your js file. var greetings = require(“./greetings.js”); access the publicly available methods of greetings.js greetings.sayHelloInEnglish(); greetings.sayHelloInSpanish(); <ref: https://www.sitepoint.com/understanding-module-exports-exports-node-js/ >
  • 21. import calc.js making a user module Import a Module import circle.js var calcObj = require(“./calc.js”); var circle = require(“./circle.js”);
  • 22. When a file is run directly from Node.js, require.main is set to its module. So, developer can determine if a file has been run directly by testing For a file foo.js, this will be true when it run via node foo.js. But, this will be false, then it run by require(“./foo”) making a user module Accessing the main module <ref: https://nodejs.org/api/modules.html#modules_modules> require.main === module
  • 23. making a user module http server module var http = require(“http”); function start() { function onRequest(request, response) { console.log(“Request Received”); response.writeHead(200, {“Content-Type”:”text/plain”}); response.write(“<h1>Welcome to HTTP Server !</h1>”); response.write(“<h2>Hello World..</h2>”); response.end(); } http.createServer(onRequest).listen(8000); console.log(“Http Server has been started”); } exports.start = start; // httpServer.js (version 1)
  • 24. making a user module using http server module var httpServer = require(“./httpServer”); httpServer.start(); // index.js (version 1) // execute index.js $ node index.js // browser index.js httpServer start()
  • 25. Http Server는 다양한 사용자 요청에 응답해야 함 조회를 위한 요청, 저장을 위한 요청 등 다양한 요청을 식별하는 routing 기능을 고려 Router request URL과 GET/POST parameter에 따라 실행할 코드를 결정 Routing: Dependency Injection Dependency Injection HTTP 요청에서 URL과 GET/POST Parameter의 추출이 필요 이 정보는 어디에 있을까 ?
  • 26. Routing: url parsing url and query parsing http://localhost:8000/start?foo=bar&hello=world url.parse(string).pathname querystring.parse(string)[“foo”] url.parse(string).query querystring.parse(string)[“hello”] request.url require “url” module require “querystring” module
  • 28. Routing: url parsing request url var http = require(“http”); var url = require(“url”); function onRequest(request, response) { console.log(request.url); response.writeHead(200, {“Content-Type”:”text/plain”}); response.write(“Hello World!”); response.end(); } http.createServer(onRequest).listen(8000); console.log(“Http Server has been started”); // httpServer.js (version 1-1)
  • 29. Routing: pathname parsing pathname parsing var http = require(“http”); var url = require(“url”); function start() { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; console.log(“Request for ” + pathname + “ received.”); response.writeHead(200, {“Content-Type”:”text/plain”}); response.write(“<h1>Welcome to HTTP Server !<h1>”); response.write(“<h2>Hello World..<h2>”); response.end(); } http.createServer(onRequest).listen(8000); console.log(“Http Server has been started”); } exports.start = start; //httpServer.js (version 2)
  • 30. Routing: router module simple router function route(pathName) { console.log(“about to route a request for “ + pathName); } exports.route = route; // router.js (version 1) index.js httpServer start() router route()inject function index.js에서 router module을 로딩하고 route()함수를 httpServer에 전달하여 실행하는 구조 Dependency Injection server 코드 변경없이 router 함수 교체가 가능
  • 31. Routing: router var httpServer = require(“./httpserver”); var router = require(“./router”); httpServer.start(router.route); // index.js (version 2) index.js with router server.js 는 start() 실행 시 route 함수를 전달하여 ‘request’ 이벤트가 발생할 때 마다 route() 함수를 호출하여 클라이언트 요청을 식별
  • 32. Routing: router var http = require(“http”); var url = require(“url”); function start(route) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; console.log(“Request for ” + pathname + “ received.”); route(pathname); // injected function call response.writeHead(200, {“Content-Type”:”text/plain”}); response.write(“<h2>Hello World..<h2>”); response.end(); } http.createServer(onRequest).listen(8000); console.log(“Http Server has been started”); } exports.start = start; //httpServer.js (version 3) httpServer with router
  • 33. Server: receives client’s request Router: route the client’s request to the request handler Request Handler: process the client’s specific request Routing: Request Handler Request Handler index.js httpServer start() router route() inject function request Handler handle
  • 34. Routing: Request Handler Request Handler //requestHandlers.js (version 0) function start() { console.log(“Request handler ‘start’ was called”); return “Welcome Start Page”; } function hello() { console.log(“Request handler ‘hello’ was called”); return “Welcome Hello Page”; } exports.start = start; //export start exports.hello = hello;
  • 35. Routing: Request Handler Request Handler //requestHandlers.js (version 1) function start() { console.log(“Request handler ‘start’ was called”); return “Welcome Start Page”; } function hello() { console.log(“Request handler ‘hello’ was called”); return “Welcome Hello Page”; } var handle = {}; handle[“/“] = start; handle[“/start”] = start; handle[“/hello”] = hello; exports.handle = handle; //export JavaScript Object
  • 36. Routing: Request Handler index.js with request handler var httpServer = require(“./httpserver”); var router = require(“./router”); var requestHandlers = require(“./requestHandlers”); httpServer.start(router.route, requestHandlers.handle); // index.js (version 3) start() 실행 시 route 함수와 handler 객체를 전달하고 ‘request’ 이벤트가 발생할 때 마다 handler 객체를 route() 함수에 전달하여 호출하여 클라이언트의 요청을 식별하고 해당 기능 수행
  • 37. Routing: Request Handler router.js with request handler function route(handle, pathName) { console.log(“about to route a request for “ + pathName); if (typeof handle[pathName] === ‘function’) { return handle[pathName](); } else { console.log(“No request handler found for “ + pathName); return “404 Not Found”; } } exports.route = route; // router.js (version 2) 요청(pathName) 별로 다른 함수를 호출
  • 38. Routing: Request Handler //httpServer.js (version 4) httpServer with router var http = require(“http”); var url = require(“url”); function start(route, handle) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; console.log(“Request for ” + pathname + “ received.”); var content = route(handle, pathname); response.writeHead(200, {“Content-Type”:”text/plain”}); response.write(content); response.end(); } http.createServer(onRequest).listen(8000); console.log(“Http Server has been started”); } exports.start = start; construct response message with return value of request handler
  • 39. Routing: Blocking From request to response HTTP Server Router Request Handlers request url forwarding invoke handler response return result return result Problem: Request Handler’s processing time may degrade the performance of HTTP Server.
  • 40. Routing: Blocking Performance //requestHandlers.js (version 1-1) function start() { console.log(“Request handler ‘start’ was called”); function sleep(msecs) { var startTime = new Date().getTime(); while(new Date().getTime() < startTime + msecs); } sleep(10000); // 10 sec waiting return “Welcome Start Page”; } Server waits util this function returns. This makes the response delay of other request.
  • 41. Routing: Non Blocking From request to response HTTP Server Router Request Handlers request pass response object pass response object response Each request handler sends the response message individually.
  • 42. Routing: Non Blocking httpServer with non-blocking //httpServer.js (version 5) var http = require(“http”); var url = require(“url”); function start(route, handle) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; console.log(“Request for ” + pathname + “ received.”); route(handle, pathname, response); } http.createServer(onRequest).listen(8000); console.log(“Http Server has been started”); } exports.start = start;
  • 43. function route(handle, pathName, response) { console.log(“about to route a request for “ + pathName); if (typeof handle[pathName] === ‘function’) { handle[pathName](response); } else { console.log(“No request handler found for “ + pathName); response.writeHead(404, {“Content-Type”:”text/plain”}); response.write(“404 Not Found”); response.end(); } } exports.route = route; // router.js (version 3) Non blocking router
  • 44. View Logic View logic for POST //start function in requestHandlers.js (version 2) function start(response) { console.log(“Request handler ‘start’ was called”); var body = “<html><head><title>First View</title>”+ “<meta charset=‘UTF-8’></head><body>“ + “로그인</br>”+ “<form action=‘/hello’ method=‘post’>” + “id: <input type=‘text’ name=‘id’></input>”+ “ <input type=‘submit’ value=‘login’/></br>”+ “pw: <input type=‘text’ name=‘pw’></input>”+ “</form></body></html>”; response.writeHead(200, {“Content-Type”:”text/html”}); response.write(body); response.end(); }
  • 45. POST data receiving Asynchronous Data receiving request.addListener(“data”, function(chunk) { // called when a new chunk of data was received } request.addListener(“end”, function() { // called when all chunks of data has been received }
  • 46. POST data receiving httpServer with POST function onRequest(request, response) { var postData =“”; var pathname = url.parse(request.url).pathname; console.log(“Request for ” + pathname + “ received.”); request.setEncoding(“utf8”); request.addListener(“data”, function(chunk) { postData += chunk; }); request.addListener(“end”, function() { route(handle, pathname, response, postData); }); } //onRequest function in httpServer.js (version 6)
  • 47. POST data receiving function route(handle, pathName, response, postData) { console.log(“about to route a request for “ + pathName); if (typeof handle[pathName] === ‘function’) { handle[pathName](response, postData); } else { console.log(“No request handler found for “ + pathName); response.writeHead(404, {“Content-Type”:”text/plain”}); response.write(“404 Not Found”); response.end(); } } exports.route = route; Router with POST // router.js (version 4)
  • 48. Pass POST data to the Client Request handler with POST function hello(response, postData) { console.log(“Request handler ‘hello’ was called”); var out = “To “ + querystring.parse(postData)[“id”]; response.writeHead(200, {“Content-Type”:”text/plain”}); response.write(out); response.write(“</br> Welcome to this World”); response.end(); } //requestHandlers.js (version 3)
  • 49. GET data receiving httpServer with GET function onRequest(request, response) { var getData =“”; var pathname = url.parse(request.url).pathname; console.log(“Request for ” + pathname + “ received.”); getData += url.parse(request.url).query; route(handle, pathname, response, getData); } //onRequest function in httpServer.js (version 7)
  • 50. GET data receiving function route(handle, pathName, response, getData) { console.log(“about to route a request for “ + pathName); if (typeof handle[pathName] === ‘function’) { handle[pathName](response, getData); } else { console.log(“No request handler found for “ + pathName); response.writeHead(404, {“Content-Type”:”text/plain”}); response.write(“404 Not Found”); response.end(); } } exports.route = route; Router with GET // router.js (version 4)
  • 51. View Logic View logic for GET //start function in requestHandlers.js (version 3) function start(response) { console.log(“Request handler ‘start’ was called”); var body = “<html><head><title>First View</title>”+ “<meta charset=‘UTF-8’></head><body>“ + “로그인</br>”+ “<form action=‘/hello’ method=‘get’>” + “id: <input type=‘text’ name=‘id’></input>”+ “ <input type=‘submit’ value=‘login’></br>”+ “pw: <input type=‘text’ name=‘pw’></input>”+ “</form></body></html>”; response.writeHead(200, {“Content-Type”:”text/html”}); response.write(body); response.end(); }
  • 52. Pass GET data to the Client Request handler with GET function hello(response, getData) { console.log(“Request handler ‘hello’ was called”); var out = “To “ + querystring.parse(getData)[“id”]; response.writeHead(200, {“Content-Type”:”text/plain”}); response.write(out); response.write(“</br> Welcome to this World”); response.end(); } //requestHandlers.js (version 4)
  • 54. E-Commerce Payment Processing Social Media Realtime Services Media Applications Enterprise Services Node: Appendix Apps suited for Node.js
  • 55. Node.js: Hello로 시작하는 Web 애플리케이션 http://www.nextree.co.kr/p8574/ The Node Beginner Book Simona Clapan, “The MEAN stack - SoCalCodeCamp - june 29th 2014” from slidehsare References