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
Ad

More Related Content

What's hot (20)

Git & GitHub for Beginners
Git & GitHub for BeginnersGit & GitHub for Beginners
Git & GitHub for Beginners
Sébastien Saunier
 
Deep dark-side of git: How git works internally
Deep dark-side of git: How git works internallyDeep dark-side of git: How git works internally
Deep dark-side of git: How git works internally
SeongJae Park
 
Git One Day Training Notes
Git One Day Training NotesGit One Day Training Notes
Git One Day Training Notes
glen_a_smith
 
Introduction to Git / Github
Introduction to Git / GithubIntroduction to Git / Github
Introduction to Git / Github
Paige Bailey
 
Git: An introduction of plumbing and porcelain commands
Git: An introduction of plumbing and porcelain commandsGit: An introduction of plumbing and porcelain commands
Git: An introduction of plumbing and porcelain commands
th507
 
Docker workshop 0507 Taichung
Docker workshop 0507 Taichung Docker workshop 0507 Taichung
Docker workshop 0507 Taichung
Paul Chao
 
Advanced Git Tutorial
Advanced Git TutorialAdvanced Git Tutorial
Advanced Git Tutorial
Sage Sharp
 
Git training
Git trainingGit training
Git training
adm_exoplatform
 
Git Tutorial
Git TutorialGit Tutorial
Git Tutorial
Pranav Kulkarni
 
Git tutorial
Git tutorialGit tutorial
Git tutorial
Pham Quy (Jack)
 
setting up a repository using GIT
setting up a repository using GITsetting up a repository using GIT
setting up a repository using GIT
Ashok Kumar Satuluri
 
Git learn from scratch
Git learn from scratchGit learn from scratch
Git learn from scratch
Mir Arif Hasan
 
Inside GitHub with Chris Wanstrath
Inside GitHub with Chris WanstrathInside GitHub with Chris Wanstrath
Inside GitHub with Chris Wanstrath
SV Ruby on Rails Meetup
 
Github - Git Training Slides: Foundations
Github - Git Training Slides: FoundationsGithub - Git Training Slides: Foundations
Github - Git Training Slides: Foundations
Lee Hanxue
 
Introduction git
Introduction gitIntroduction git
Introduction git
Dian Sigit Prastowo
 
手把手帶你學Docker 03042017
手把手帶你學Docker 03042017手把手帶你學Docker 03042017
手把手帶你學Docker 03042017
Paul Chao
 
Git introduction
Git introductionGit introduction
Git introduction
satyendrajaladi
 
Intro to Git and GitHub
Intro to Git and GitHubIntro to Git and GitHub
Intro to Git and GitHub
Matthew McCullough
 
Git basics for beginners
Git basics for beginnersGit basics for beginners
Git basics for beginners
PravallikaTammisetty
 
Git Version Control System
Git Version Control SystemGit Version Control System
Git Version Control System
KMS Technology
 
Deep dark-side of git: How git works internally
Deep dark-side of git: How git works internallyDeep dark-side of git: How git works internally
Deep dark-side of git: How git works internally
SeongJae Park
 
Git One Day Training Notes
Git One Day Training NotesGit One Day Training Notes
Git One Day Training Notes
glen_a_smith
 
Introduction to Git / Github
Introduction to Git / GithubIntroduction to Git / Github
Introduction to Git / Github
Paige Bailey
 
Git: An introduction of plumbing and porcelain commands
Git: An introduction of plumbing and porcelain commandsGit: An introduction of plumbing and porcelain commands
Git: An introduction of plumbing and porcelain commands
th507
 
Docker workshop 0507 Taichung
Docker workshop 0507 Taichung Docker workshop 0507 Taichung
Docker workshop 0507 Taichung
Paul Chao
 
Advanced Git Tutorial
Advanced Git TutorialAdvanced Git Tutorial
Advanced Git Tutorial
Sage Sharp
 
Git learn from scratch
Git learn from scratchGit learn from scratch
Git learn from scratch
Mir Arif Hasan
 
Github - Git Training Slides: Foundations
Github - Git Training Slides: FoundationsGithub - Git Training Slides: Foundations
Github - Git Training Slides: Foundations
Lee Hanxue
 
手把手帶你學Docker 03042017
手把手帶你學Docker 03042017手把手帶你學Docker 03042017
手把手帶你學Docker 03042017
Paul Chao
 
Git Version Control System
Git Version Control SystemGit Version Control System
Git Version Control System
KMS Technology
 

Viewers also liked (15)

COMO CREAR UN TEXTO
COMO CREAR UN TEXTOCOMO CREAR UN TEXTO
COMO CREAR UN TEXTO
estefania720
 
by the numbers
by the numbersby the numbers
by the numbers
Matt Batchelder
 
Sistemas operativos
Sistemas operativosSistemas operativos
Sistemas operativos
andres torres
 
Renting OCNJ
Renting OCNJRenting OCNJ
Renting OCNJ
Shovon Pramanik
 
салмина алина 1921_информатика
салмина алина 1921_информатикасалмина алина 1921_информатика
салмина алина 1921_информатика
alinochkavedenina
 
Perdiqua
PerdiquaPerdiqua
Perdiqua
ppcamuno
 
Riler v California (REAL)
Riler v California (REAL)Riler v California (REAL)
Riler v California (REAL)
CPellegrini15
 
Mec�nica dos fluidos
Mec�nica dos fluidosMec�nica dos fluidos
Mec�nica dos fluidos
Diego Machado
 
Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
Muhazzab Chouhadry
 
Maslow's Needs
Maslow's NeedsMaslow's Needs
Maslow's Needs
CoombeMedia1
 
Objectives of ncert asw pdf
Objectives of ncert asw pdfObjectives of ncert asw pdf
Objectives of ncert asw pdf
aswathymaths
 
Queue in Data Structure
Queue in Data StructureQueue in Data Structure
Queue in Data Structure
Muhazzab Chouhadry
 
Els paisatges agraris (estela gil 3re) (2)
Els paisatges agraris (estela gil 3re) (2)Els paisatges agraris (estela gil 3re) (2)
Els paisatges agraris (estela gil 3re) (2)
Joan Piña Torres
 
Ebola
EbolaEbola
Ebola
aliciadiez
 
Alzheimer
AlzheimerAlzheimer
Alzheimer
aliciadiez
 
COMO CREAR UN TEXTO
COMO CREAR UN TEXTOCOMO CREAR UN TEXTO
COMO CREAR UN TEXTO
estefania720
 
салмина алина 1921_информатика
салмина алина 1921_информатикасалмина алина 1921_информатика
салмина алина 1921_информатика
alinochkavedenina
 
Riler v California (REAL)
Riler v California (REAL)Riler v California (REAL)
Riler v California (REAL)
CPellegrini15
 
Mec�nica dos fluidos
Mec�nica dos fluidosMec�nica dos fluidos
Mec�nica dos fluidos
Diego Machado
 
Objectives of ncert asw pdf
Objectives of ncert asw pdfObjectives of ncert asw pdf
Objectives of ncert asw pdf
aswathymaths
 
Els paisatges agraris (estela gil 3re) (2)
Els paisatges agraris (estela gil 3re) (2)Els paisatges agraris (estela gil 3re) (2)
Els paisatges agraris (estela gil 3re) (2)
Joan Piña Torres
 
Ad

Similar to 5.node js (20)

soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
soft-shake.ch
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.js
Ayush Mishra
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
Gonzalo Ayuso
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
Yiguang Hu
 
Node.js 1, 2, 3
Node.js 1, 2, 3Node.js 1, 2, 3
Node.js 1, 2, 3
Jian-Hong Pan
 
Node.js web-based Example :Run a local server in order to start using node.js...
Node.js web-based Example :Run a local server in order to start using node.js...Node.js web-based Example :Run a local server in order to start using node.js...
Node.js web-based Example :Run a local server in order to start using node.js...
Kongu Engineering College, Perundurai, Erode
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
FITC
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
Siarzh Miadzvedzeu
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
NodeJS
NodeJSNodeJS
NodeJS
Alok Guha
 
Node js getting started
Node js getting startedNode js getting started
Node js getting started
Pallavi Srivastava
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentation
Stuart (Pid) Williams
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Somkiat Puisungnoen
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
Yevgeniy Brikman
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
Parth Joshi
 
Sanjeev ghai 12
Sanjeev ghai 12Sanjeev ghai 12
Sanjeev ghai 12
Praveen kumar
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
Sudar Muthu
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
async_io
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
soft-shake.ch
 
An Overview of Node.js
An Overview of Node.jsAn Overview of Node.js
An Overview of Node.js
Ayush Mishra
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
Gonzalo Ayuso
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
Yiguang Hu
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
FITC
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
Vikash Singh
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentation
Stuart (Pid) Williams
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
Yevgeniy Brikman
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
Parth Joshi
 
Introduction to node.js GDD
Introduction to node.js GDDIntroduction to node.js GDD
Introduction to node.js GDD
Sudar Muthu
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
async_io
 
Ad

More from Geunhyung Kim (7)

7. sorting
7. sorting7. sorting
7. sorting
Geunhyung Kim
 
6. binary tree
6. binary tree6. binary tree
6. binary tree
Geunhyung Kim
 
5. queue
5. queue5. queue
5. queue
Geunhyung Kim
 
4. stack
4. stack4. stack
4. stack
Geunhyung Kim
 
1. introduction to algorithm
1. introduction to algorithm1. introduction to algorithm
1. introduction to algorithm
Geunhyung Kim
 
11. git basic
11. git basic11. git basic
11. git basic
Geunhyung Kim
 
3. linked list
3. linked list3. linked list
3. linked list
Geunhyung Kim
 

Recently uploaded (20)

Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025Adobe Master Collection CC Crack Advance Version 2025
Adobe Master Collection CC Crack Advance Version 2025
kashifyounis067
 
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025Why Orangescrum Is a Game Changer for Construction Companies in 2025
Why Orangescrum Is a Game Changer for Construction Companies in 2025
Orangescrum
 
WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)WinRAR Crack for Windows (100% Working 2025)
WinRAR Crack for Windows (100% Working 2025)
sh607827
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRYLEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
LEARN SEO AND INCREASE YOUR KNOWLDGE IN SOFTWARE INDUSTRY
NidaFarooq10
 
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 

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