SlideShare uma empresa Scribd logo
1 de 48
Baixar para ler offline
진짜 기초 
NHN NEXT 김우진
node.js? 
“서버사이드 JavaScript”
목표 
“서버가 하는 일을 익히는 것.” 
“node.js의 기본적인 동작을 익히는 것.”
Hello World! 
// helloworld.js 
console.log("Hello World!"); 
// terminal 
$ node helloworld.js
우리가 만들 거. 
이름을 입력하세요. 안녕하세요. 김우진 님 
김우진 입력 
http://localhost:8888/start http://localhost:8888/hello 
쉽죠?
우리가 필요한 거. 
요청 
HTTP서버 : 웹페이지 제공 
라우터 : 요청과 요청을 처리할 핸들러들을 연결 
요청 핸들러 : 요청을 만족시키기위한 핸들러 
뷰 로직 : 브라우저로 콘텐트를 만들어 보내기 위한 로직 
응답
기본서버 만들기. 
요청 
HTTP서버 : 웹페이지 제공 
라우터 : 요청과 요청을 처리할 핸들러들을 연결 
요청 핸들러 : 요청을 만족시키기위한 핸들러 
뷰 로직 : 브라우저로 콘텐트를 만들어 보내기 위한 로직 
응답
기본서버 만들기. 
// server.js 
var http = require("http"); 
http.createServer(function (request, response) { 
response.writeHead(200, {"Content-Type" : "text/plain"}); 
response.write("Hello World!"); 
response.end(); 
}).listen(8888); 
// terminal 
$ node server.js 
// browser 
http://localhost:8888
기본서버 만들기. - 함수전달 
// server.js 
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(8888); 
console.log("Server has started."); 
이 함수는 클라이언트의 요청을 받으면 
거꾸로 호출(callback)된다.
기본서버 만들기. - 모듈화 
// server.js 
var http = require("http"); 
function start() { 
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(8888); 
console.log("Server has started."); 
} 
exports.start = start;
기본서버 만들기. - 모듈화 
// index.js 
var server = require("./server"); 
server.start(); 
// terminal 
$ node index.js 
// browser 
http://localhost:8888
요청 
HTTP서버 : 웹페이지 제공 
라우터 : 요청과 요청을 처리할 핸들러들을 연결 
요청 핸들러 : 요청을 만족시키기위한 핸들러 
뷰 로직 : 브라우저로 콘텐트를 만들어 보내기 위한 로직 
응답 
요청을 route
요청을 route 
url.parse(string).query 
| 
url.parse(string).pathname | 
| | 
| | 
------ ------------------- 
http://localhost:8888/start?foo=bar&hello=world 
--- ----- 
| | 
| | 
querystring.parse(string)["foo"] | 
| 
querystring.parse(string)["hello"]
요청을 route 
// server.js 
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("Hello World"); 
response.end(); 
} 
http.createServer(onRequest).listen(8888); 
console.log("Server has started."); 
} 
exports.start = start;
요청을 route 
// server.js 
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); 
response.writeHead(200, {"Content-Type": "text/plain"}); 
response.write("Hello World"); 
response.end(); 
} 
http.createServer(onRequest).listen(8888); 
console.log("Server has started."); 
} 
exports.start = start;
요청을 route 
// router.js 
function route(pathname) { 
console.log("About to route a request for " + pathname); 
} 
exports.route = route;
요청을 route 
// index.js 
var server = require("./server"); 
var router = require("./router"); 
server.start(router.route); 
// terminal 
$ node index.js 
// browser 
http://localhost:8888/something
request handler 
요청 
HTTP서버 : 웹페이지 제공 
라우터 : 요청과 요청을 처리할 핸들러들을 연결 
요청 핸들러 : 요청을 만족시키기위한 핸들러 
뷰 로직 : 브라우저로 콘텐트를 만들어 보내기 위한 로직 
응답
request handler 
요청별로 다른 함수에서 처리하고 싶다! 
// requestHandlers.js 
function start() { 
console.log("Request handler 'start' was called."); 
} 
function hello() { 
console.log("Request handler 'hello' was called."); 
} 
exports.start = start; 
exports.hello = hello;
request handler 
요청별로 다른 함수에서 처리하고 싶다! 
// index.js 
var server = require("./server"); 
var router = require("./router"); 
var requestHandlers = require("./requestHandlers"); 
// path와 연결되는 함수의 정보를 저장. 
var handle = {} 
handle["/"] = requestHandlers.start; 
handle["/start"] = requestHandlers.start; 
handle["/hello"] = requestHandlers.hello; 
server.start(router.route, handle);
request handler 
요청별로 다른 함수에서 처리하고 싶다! 
// server.js 
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.writeHead(200, {"Content-Type": "text/plain"}); 
response.write("Hello World"); 
response.end(); 
} 
http.createServer(onRequest).listen(8888); 
console.log("Server has started."); 
}
request handler 
요청별로 다른 함수에서 처리하고 싶다! 
// router.js 
function route(handle, pathname) { 
console.log("About to route a request for " + pathname); 
if (typeof handle[pathname] === 'function') { 
handle[pathname](); 
} else { 
console.log("No request handler found for " + pathname); 
} 
} 
exports.route = route;
request handler가 응답하게 
// requestHandlers.js 
function start() { 
console.log("Request handler 'start' was called."); 
return "Hello Start"; 
} 
function hello() { 
console.log("Request handler 'hello' was called."); 
return "Hello Hello"; 
} 
exports.start = start; 
exports.hello = hello;
request handler가 응답하게 
// router.js 
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;
request handler가 응답하게 
// server.js 
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."); 
response.writeHead(200, {"Content-Type": "text/plain"}); 
var content = route(handle, pathname); 
response.write(content); 
response.end(); 
} 
http.createServer(onRequest).listen(8888); 
console.log("Server has started."); 
} 
exports.start = start;
request handler가 응답하게 
// terminal 
$ node index.js 
// browser 
http://localhost:8888/ 
http://localhost:8888/start 
http://localhost:8888/hello 
http://localhost:8888/something
Blocking 과 Non-Blocking 
// requestHandlers.js 
function start() { 
console.log("Request handler 'start' was called."); 
function sleep(milliSeconds) { 
var startTime = new Date().getTime(); 
while (new Date().getTime() < startTime + milliSeconds); 
} 
// 10초간 기다려! 
sleep(10000); 
// 이 함수가 리턴 할 때까지 서버가 기다린다. 
return "Hello Start"; 
}
Blocking 과 Non-Blocking 
// terminal 
$ node index.js 
// 여러개 browser에서 동시에 
http://localhost:8888/ 
http://localhost:8888/start 
http://localhost:8888/hello 
http://localhost:8888/something 
동시에 여러명이 접속할 때 문제가 발생! 
-> 혼자만 기다리면 되는데 여러명을 기다리게 함.
Blocking 과 Non-Blocking 
“node.js는 Single Thread, 
동시작업을 Event Loop를 실행하여 처리”
Blocking 과 Non-Blocking 
Event Loop? 
“헤이, probablyExpensiveFunction(), 니 일을 해줘. 하지만 나 
Single Node.js 쓰레드는 네가 끝낼 때까지 여기서 기다리지 않을거 
야. 네 아래에 있는 코드 라인을 계속 실행할거야. 그러니 여기 이 
callbackFunction()을 가져가서 네가 너의 비싼 일을 모두 끝냈을 때 
호출(callback)해 주겠니? 고마워!”
Blocking 과 Non-Blocking 
HTTP서버 
라우터 
리턴(기다려!) 
요청 핸들러 
HTTP서버 
response 객체를 넘김 
라우터 
response 객체를 넘김 
요청 핸들러 
요청 응답 
전달 
전달 리턴(기다려!) 
요청 
응답 
요청 핸들러에서 응답을 처리하게
Blocking 과 Non-Blocking 
// server.js 
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(8888); 
console.log("Server has started."); 
} 
exports.start = start;
Blocking 과 Non-Blocking 
// router.js 
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;
Blocking 과 Non-Blocking 
// requestHandlers.js 
function start(response) { 
console.log("Request handler 'start' was called."); 
// 비동기 Non-Blocking 함수를 사용. 
setTimeout(function(){ 
response.writeHead(200, {"Content-Type": "text/plain"}); 
response.write("Hello Start"); 
response.end(); 
}, 10000); 
} 
function hello(response) { 
console.log("Request handler 'hello' was called."); 
response.writeHead(200, {"Content-Type": "text/plain"}); 
response.write("Hello Hello"); 
response.end(); 
} 
exports.start = start; 
exports.hello = hello;
Blocking 과 Non-Blocking 
// terminal 
$ node index.js 
// 여러개 browser에서 동시에 
http://localhost:8888/ 
http://localhost:8888/start 
http://localhost:8888/hello 
http://localhost:8888/something 
해결! 하지만 큰 의미는 없으니 지웁시다.
Blocking 과 Non-Blocking 
// requestHandlers.js 
function start(response) { 
console.log("Request handler 'start' was called.”); 
response.writeHead(200, {"Content-Type": "text/plain"}); 
response.write("Hello Start"); 
response.end(); 
} 
function hello(response) { 
console.log("Request handler 'hello' was called."); 
response.writeHead(200, {"Content-Type": "text/plain"}); 
response.write("Hello Hello"); 
response.end(); 
} 
exports.start = start; 
exports.hello = hello;
Blocking 과 Non-Blocking 
여기서 기억할 점. 
“Javascript엔 만나자마자 Event Loop에 
넣고 다음줄로 넘어가는 함수가 있다.” 
(다 그런건 아니다.)
뷰 로직을 만들고 연동하기. 
요청 
HTTP서버 : 웹페이지 제공 
라우터 : 요청과 요청을 처리할 핸들러들을 연결 
요청 핸들러 : 요청을 만족시키기위한 핸들러 
뷰 로직 : 브라우저로 콘텐트를 만들어 보내기 위한 로직 
응답
뷰 로직을 만들고 연동하기. 
// requestHandlers.js 
function start(response) { 
console.log("Request handler 'start' was called."); 
var body = ‘<html>'+'<head>'+ 
'<meta http-equiv="Content-Type" content="text/html; '+ 
'charset=UTF-8" />'+ 
'</head>'+ '<body>'+ 
'이름을 입력하세요.'+ '<br>'+ 
'<form action="/hello" method="post">'+ 
'<input type="text" name="text"></input>'+ 
'<input type="submit" value="입력" />'+ 
'</form>'+'</body>'+'</html>'; 
response.writeHead(200, {"Content-Type": "text/html"}); 
response.write(body); 
response.end(); 
}
뷰 로직을 만들고 연동하기. 
POST Data를 비동기로 받기. 
request.addListener("data", function(chunk) { 
// called when a new chunk of data was received 
}); 
request.addListener("end", function() { 
// called when all chunks of data have been received 
});
뷰 로직을 만들고 연동하기. 
POST Data를 비동기로 받기. 
// server.js 
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(postDataChunk) { 
postData += postDataChunk; 
console.log("Received POST data chunk '"+ 
postDataChunk + "'."); 
}); 
request.addListener("end", function() { 
route(handle, pathname, response, postData); 
}); 
}
뷰 로직을 만들고 연동하기. 
POST Data를 비동기로 받기. 
// router.js 
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(); 
} 
}
뷰 로직을 만들고 연동하기. 
POST Data를 받아서 사용하기. 
// requestHandlers.js 
function hello(response, postData) { 
console.log("Request handler 'hello' was called."); 
response.writeHead(200, {"Content-Type": "text/plain"}); 
response.write("안녕하세요. "+ postData + "님"); 
response.end(); 
}
뷰 로직을 만들고 연동하기. 
POST Data를 받아서 사용하기. -> text만 가져오기. 
// requestHandlers.js 
var querystring = require("querystring"); 
// ... 
function hello(response, postData) { 
console.log("Request handler 'upload' was called."); 
response.writeHead(200, {"Content-Type": "text/plain"}); 
response.write("안녕하세요. "+ 
querystring.parse(postData).text + "님"); 
response.end(); 
}
뷰 로직을 만들고 연동하기. 
// terminal 
$ node index.js 
// browser 
http://localhost:8888/ 
완성!
공부하기 
GET Method와 POST Method의 차이점 
과제 
같은 로직을 GET Method를 사용하여 만들어 보기.
reference 
http://www.nodebeginner.org/index-kr.html
끝

Mais conteúdo relacionado

Mais procurados

막하는스터디 두번째만남 Express(20151025)
막하는스터디 두번째만남 Express(20151025)막하는스터디 두번째만남 Express(20151025)
막하는스터디 두번째만남 Express(20151025)연웅 조
 
Resource Handling in Spring MVC
Resource Handling in Spring MVCResource Handling in Spring MVC
Resource Handling in Spring MVCArawn Park
 
파크히어 Realm 사용 사례
파크히어 Realm 사용 사례파크히어 Realm 사용 사례
파크히어 Realm 사용 사례선협 이
 
막하는 스터디 네 번째 만남 AngularJs (20151108)
막하는 스터디 네 번째 만남 AngularJs (20151108)막하는 스터디 네 번째 만남 AngularJs (20151108)
막하는 스터디 네 번째 만남 AngularJs (20151108)연웅 조
 
Nodejs 발표자료
Nodejs 발표자료Nodejs 발표자료
Nodejs 발표자료shanka2
 
5-5. html5 connectivity
5-5. html5 connectivity5-5. html5 connectivity
5-5. html5 connectivityJinKyoungHeo
 
Node.js의 도입과 활용
Node.js의 도입과 활용Node.js의 도입과 활용
Node.js의 도입과 활용Jin wook
 
Startup JavaScript 7 - Node.JS 기초
Startup JavaScript 7 - Node.JS 기초Startup JavaScript 7 - Node.JS 기초
Startup JavaScript 7 - Node.JS 기초Circulus
 
Secrets of the JavaScript Ninja - Chapter 12. DOM modification
Secrets of the JavaScript Ninja - Chapter 12. DOM modificationSecrets of the JavaScript Ninja - Chapter 12. DOM modification
Secrets of the JavaScript Ninja - Chapter 12. DOM modificationHyuncheol Jeon
 
Angular2 router&http
Angular2 router&httpAngular2 router&http
Angular2 router&httpDong Jun Kwon
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍NAVER D2
 
ECMAScript 6의 새로운 것들!
ECMAScript 6의 새로운 것들!ECMAScript 6의 새로운 것들!
ECMAScript 6의 새로운 것들!WooYoung Cho
 
Web Components 101 polymer & brick
Web Components 101 polymer & brickWeb Components 101 polymer & brick
Web Components 101 polymer & brickyongwoo Jeon
 
Javascript everywhere - Node.js | Devon 2012
Javascript everywhere - Node.js | Devon 2012Javascript everywhere - Node.js | Devon 2012
Javascript everywhere - Node.js | Devon 2012Daum DNA
 
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기XpressEngine
 
Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나JeongHun Byeon
 
Startup JavaScript 9 - Socket.IO 실시간 통신
Startup JavaScript 9 - Socket.IO 실시간 통신Startup JavaScript 9 - Socket.IO 실시간 통신
Startup JavaScript 9 - Socket.IO 실시간 통신Circulus
 

Mais procurados (20)

막하는스터디 두번째만남 Express(20151025)
막하는스터디 두번째만남 Express(20151025)막하는스터디 두번째만남 Express(20151025)
막하는스터디 두번째만남 Express(20151025)
 
Resource Handling in Spring MVC
Resource Handling in Spring MVCResource Handling in Spring MVC
Resource Handling in Spring MVC
 
파크히어 Realm 사용 사례
파크히어 Realm 사용 사례파크히어 Realm 사용 사례
파크히어 Realm 사용 사례
 
막하는 스터디 네 번째 만남 AngularJs (20151108)
막하는 스터디 네 번째 만남 AngularJs (20151108)막하는 스터디 네 번째 만남 AngularJs (20151108)
막하는 스터디 네 번째 만남 AngularJs (20151108)
 
Nodejs 발표자료
Nodejs 발표자료Nodejs 발표자료
Nodejs 발표자료
 
5-5. html5 connectivity
5-5. html5 connectivity5-5. html5 connectivity
5-5. html5 connectivity
 
Node.js 기본과정
Node.js 기본과정Node.js 기본과정
Node.js 기본과정
 
Node.js의 도입과 활용
Node.js의 도입과 활용Node.js의 도입과 활용
Node.js의 도입과 활용
 
Startup JavaScript 7 - Node.JS 기초
Startup JavaScript 7 - Node.JS 기초Startup JavaScript 7 - Node.JS 기초
Startup JavaScript 7 - Node.JS 기초
 
Secrets of the JavaScript Ninja - Chapter 12. DOM modification
Secrets of the JavaScript Ninja - Chapter 12. DOM modificationSecrets of the JavaScript Ninja - Chapter 12. DOM modification
Secrets of the JavaScript Ninja - Chapter 12. DOM modification
 
Angular2 router&http
Angular2 router&httpAngular2 router&http
Angular2 router&http
 
Web workers
Web workersWeb workers
Web workers
 
[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍[1B4]안드로이드 동시성_프로그래밍
[1B4]안드로이드 동시성_프로그래밍
 
4-3. jquery
4-3. jquery4-3. jquery
4-3. jquery
 
ECMAScript 6의 새로운 것들!
ECMAScript 6의 새로운 것들!ECMAScript 6의 새로운 것들!
ECMAScript 6의 새로운 것들!
 
Web Components 101 polymer & brick
Web Components 101 polymer & brickWeb Components 101 polymer & brick
Web Components 101 polymer & brick
 
Javascript everywhere - Node.js | Devon 2012
Javascript everywhere - Node.js | Devon 2012Javascript everywhere - Node.js | Devon 2012
Javascript everywhere - Node.js | Devon 2012
 
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
 
Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나
 
Startup JavaScript 9 - Socket.IO 실시간 통신
Startup JavaScript 9 - Socket.IO 실시간 통신Startup JavaScript 9 - Socket.IO 실시간 통신
Startup JavaScript 9 - Socket.IO 실시간 통신
 

Semelhante a 진짜기초 Node.js

Node js[stg]onimusha 20140822
Node js[stg]onimusha 20140822Node js[stg]onimusha 20140822
Node js[stg]onimusha 20140822병헌 정
 
vine webdev
vine webdevvine webdev
vine webdevdcfc1997
 
Ksug 세미나 (윤성준) (20121208)
Ksug 세미나 (윤성준) (20121208)Ksug 세미나 (윤성준) (20121208)
Ksug 세미나 (윤성준) (20121208)Sungjoon Yoon
 
챗봇 시작해보기
챗봇 시작해보기챗봇 시작해보기
챗봇 시작해보기성일 한
 
Node.js and react
Node.js and reactNode.js and react
Node.js and reactHyungKuIm
 
Startup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JSStartup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JSCirculus
 
처음배우는 자바스크립트, 제이쿼리 #4
처음배우는 자바스크립트, 제이쿼리 #4처음배우는 자바스크립트, 제이쿼리 #4
처음배우는 자바스크립트, 제이쿼리 #4성일 한
 
Ryu with OpenFlow 1.3, REST API
Ryu with OpenFlow 1.3, REST APIRyu with OpenFlow 1.3, REST API
Ryu with OpenFlow 1.3, REST APIjieun kim
 
vert.x 를 활용한 분산서버 개발하기
vert.x 를 활용한 분산서버 개발하기vert.x 를 활용한 분산서버 개발하기
vert.x 를 활용한 분산서버 개발하기John Kim
 
Ji 개발 리뷰 (신림프로그래머)
Ji 개발 리뷰 (신림프로그래머)Ji 개발 리뷰 (신림프로그래머)
Ji 개발 리뷰 (신림프로그래머)beom kyun choi
 
Mean 스택을 사용한 IoT 개발
Mean 스택을 사용한 IoT 개발Mean 스택을 사용한 IoT 개발
Mean 스택을 사용한 IoT 개발Jay Park
 
5-4. html5 offline and storage
5-4. html5 offline and storage5-4. html5 offline and storage
5-4. html5 offline and storageJinKyoungHeo
 
ASP.NET Web API를 활용한 RESTful 서비스 개발
ASP.NET Web API를 활용한 RESTful 서비스 개발ASP.NET Web API를 활용한 RESTful 서비스 개발
ASP.NET Web API를 활용한 RESTful 서비스 개발SangHoon Han
 

Semelhante a 진짜기초 Node.js (20)

Node js[stg]onimusha 20140822
Node js[stg]onimusha 20140822Node js[stg]onimusha 20140822
Node js[stg]onimusha 20140822
 
4-2. ajax
4-2. ajax4-2. ajax
4-2. ajax
 
Html5 performance
Html5 performanceHtml5 performance
Html5 performance
 
vine webdev
vine webdevvine webdev
vine webdev
 
Nodejs express
Nodejs expressNodejs express
Nodejs express
 
Ksug 세미나 (윤성준) (20121208)
Ksug 세미나 (윤성준) (20121208)Ksug 세미나 (윤성준) (20121208)
Ksug 세미나 (윤성준) (20121208)
 
챗봇 시작해보기
챗봇 시작해보기챗봇 시작해보기
챗봇 시작해보기
 
Node.js and react
Node.js and reactNode.js and react
Node.js and react
 
Node.js 첫걸음
Node.js 첫걸음Node.js 첫걸음
Node.js 첫걸음
 
Startup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JSStartup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JS
 
처음배우는 자바스크립트, 제이쿼리 #4
처음배우는 자바스크립트, 제이쿼리 #4처음배우는 자바스크립트, 제이쿼리 #4
처음배우는 자바스크립트, 제이쿼리 #4
 
Spring boot actuator
Spring boot   actuatorSpring boot   actuator
Spring boot actuator
 
Ryu with OpenFlow 1.3, REST API
Ryu with OpenFlow 1.3, REST APIRyu with OpenFlow 1.3, REST API
Ryu with OpenFlow 1.3, REST API
 
vert.x 를 활용한 분산서버 개발하기
vert.x 를 활용한 분산서버 개발하기vert.x 를 활용한 분산서버 개발하기
vert.x 를 활용한 분산서버 개발하기
 
One-day-codelab
One-day-codelabOne-day-codelab
One-day-codelab
 
Ji 개발 리뷰 (신림프로그래머)
Ji 개발 리뷰 (신림프로그래머)Ji 개발 리뷰 (신림프로그래머)
Ji 개발 리뷰 (신림프로그래머)
 
Mean 스택을 사용한 IoT 개발
Mean 스택을 사용한 IoT 개발Mean 스택을 사용한 IoT 개발
Mean 스택을 사용한 IoT 개발
 
5-4. html5 offline and storage
5-4. html5 offline and storage5-4. html5 offline and storage
5-4. html5 offline and storage
 
Node.js at OKJSP
Node.js at OKJSPNode.js at OKJSP
Node.js at OKJSP
 
ASP.NET Web API를 활용한 RESTful 서비스 개발
ASP.NET Web API를 활용한 RESTful 서비스 개발ASP.NET Web API를 활용한 RESTful 서비스 개발
ASP.NET Web API를 활용한 RESTful 서비스 개발
 

Mais de Woo Jin Kim

Berry - Honghap Valley DEMO Day Presentation
Berry - Honghap Valley DEMO Day PresentationBerry - Honghap Valley DEMO Day Presentation
Berry - Honghap Valley DEMO Day PresentationWoo Jin Kim
 
Berry business plan
Berry business planBerry business plan
Berry business planWoo Jin Kim
 
berry business plan
berry business planberry business plan
berry business planWoo Jin Kim
 
Fast render 톺아보기
Fast render 톺아보기Fast render 톺아보기
Fast render 톺아보기Woo Jin Kim
 
Command pattern 김우진
Command pattern 김우진Command pattern 김우진
Command pattern 김우진Woo Jin Kim
 
Git branch stregagy & case study
Git branch stregagy & case studyGit branch stregagy & case study
Git branch stregagy & case studyWoo Jin Kim
 

Mais de Woo Jin Kim (7)

Berry - Honghap Valley DEMO Day Presentation
Berry - Honghap Valley DEMO Day PresentationBerry - Honghap Valley DEMO Day Presentation
Berry - Honghap Valley DEMO Day Presentation
 
Berry business plan
Berry business planBerry business plan
Berry business plan
 
berry business plan
berry business planberry business plan
berry business plan
 
Fast render 톺아보기
Fast render 톺아보기Fast render 톺아보기
Fast render 톺아보기
 
Command pattern 김우진
Command pattern 김우진Command pattern 김우진
Command pattern 김우진
 
Memento pattern
Memento patternMemento pattern
Memento pattern
 
Git branch stregagy & case study
Git branch stregagy & case studyGit branch stregagy & case study
Git branch stregagy & case study
 

진짜기초 Node.js

  • 1. 진짜 기초 NHN NEXT 김우진
  • 3. 목표 “서버가 하는 일을 익히는 것.” “node.js의 기본적인 동작을 익히는 것.”
  • 4. Hello World! // helloworld.js console.log("Hello World!"); // terminal $ node helloworld.js
  • 5. 우리가 만들 거. 이름을 입력하세요. 안녕하세요. 김우진 님 김우진 입력 http://localhost:8888/start http://localhost:8888/hello 쉽죠?
  • 6. 우리가 필요한 거. 요청 HTTP서버 : 웹페이지 제공 라우터 : 요청과 요청을 처리할 핸들러들을 연결 요청 핸들러 : 요청을 만족시키기위한 핸들러 뷰 로직 : 브라우저로 콘텐트를 만들어 보내기 위한 로직 응답
  • 7. 기본서버 만들기. 요청 HTTP서버 : 웹페이지 제공 라우터 : 요청과 요청을 처리할 핸들러들을 연결 요청 핸들러 : 요청을 만족시키기위한 핸들러 뷰 로직 : 브라우저로 콘텐트를 만들어 보내기 위한 로직 응답
  • 8. 기본서버 만들기. // server.js var http = require("http"); http.createServer(function (request, response) { response.writeHead(200, {"Content-Type" : "text/plain"}); response.write("Hello World!"); response.end(); }).listen(8888); // terminal $ node server.js // browser http://localhost:8888
  • 9. 기본서버 만들기. - 함수전달 // server.js 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(8888); console.log("Server has started."); 이 함수는 클라이언트의 요청을 받으면 거꾸로 호출(callback)된다.
  • 10. 기본서버 만들기. - 모듈화 // server.js var http = require("http"); function start() { 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(8888); console.log("Server has started."); } exports.start = start;
  • 11. 기본서버 만들기. - 모듈화 // index.js var server = require("./server"); server.start(); // terminal $ node index.js // browser http://localhost:8888
  • 12. 요청 HTTP서버 : 웹페이지 제공 라우터 : 요청과 요청을 처리할 핸들러들을 연결 요청 핸들러 : 요청을 만족시키기위한 핸들러 뷰 로직 : 브라우저로 콘텐트를 만들어 보내기 위한 로직 응답 요청을 route
  • 13. 요청을 route url.parse(string).query | url.parse(string).pathname | | | | | ------ ------------------- http://localhost:8888/start?foo=bar&hello=world --- ----- | | | | querystring.parse(string)["foo"] | | querystring.parse(string)["hello"]
  • 14. 요청을 route // server.js 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("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start;
  • 15. 요청을 route // server.js 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); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start;
  • 16. 요청을 route // router.js function route(pathname) { console.log("About to route a request for " + pathname); } exports.route = route;
  • 17. 요청을 route // index.js var server = require("./server"); var router = require("./router"); server.start(router.route); // terminal $ node index.js // browser http://localhost:8888/something
  • 18. request handler 요청 HTTP서버 : 웹페이지 제공 라우터 : 요청과 요청을 처리할 핸들러들을 연결 요청 핸들러 : 요청을 만족시키기위한 핸들러 뷰 로직 : 브라우저로 콘텐트를 만들어 보내기 위한 로직 응답
  • 19. request handler 요청별로 다른 함수에서 처리하고 싶다! // requestHandlers.js function start() { console.log("Request handler 'start' was called."); } function hello() { console.log("Request handler 'hello' was called."); } exports.start = start; exports.hello = hello;
  • 20. request handler 요청별로 다른 함수에서 처리하고 싶다! // index.js var server = require("./server"); var router = require("./router"); var requestHandlers = require("./requestHandlers"); // path와 연결되는 함수의 정보를 저장. var handle = {} handle["/"] = requestHandlers.start; handle["/start"] = requestHandlers.start; handle["/hello"] = requestHandlers.hello; server.start(router.route, handle);
  • 21. request handler 요청별로 다른 함수에서 처리하고 싶다! // server.js 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.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); }
  • 22. request handler 요청별로 다른 함수에서 처리하고 싶다! // router.js function route(handle, pathname) { console.log("About to route a request for " + pathname); if (typeof handle[pathname] === 'function') { handle[pathname](); } else { console.log("No request handler found for " + pathname); } } exports.route = route;
  • 23. request handler가 응답하게 // requestHandlers.js function start() { console.log("Request handler 'start' was called."); return "Hello Start"; } function hello() { console.log("Request handler 'hello' was called."); return "Hello Hello"; } exports.start = start; exports.hello = hello;
  • 24. request handler가 응답하게 // router.js 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;
  • 25. request handler가 응답하게 // server.js 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."); response.writeHead(200, {"Content-Type": "text/plain"}); var content = route(handle, pathname); response.write(content); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start;
  • 26. request handler가 응답하게 // terminal $ node index.js // browser http://localhost:8888/ http://localhost:8888/start http://localhost:8888/hello http://localhost:8888/something
  • 27. Blocking 과 Non-Blocking // requestHandlers.js function start() { console.log("Request handler 'start' was called."); function sleep(milliSeconds) { var startTime = new Date().getTime(); while (new Date().getTime() < startTime + milliSeconds); } // 10초간 기다려! sleep(10000); // 이 함수가 리턴 할 때까지 서버가 기다린다. return "Hello Start"; }
  • 28. Blocking 과 Non-Blocking // terminal $ node index.js // 여러개 browser에서 동시에 http://localhost:8888/ http://localhost:8888/start http://localhost:8888/hello http://localhost:8888/something 동시에 여러명이 접속할 때 문제가 발생! -> 혼자만 기다리면 되는데 여러명을 기다리게 함.
  • 29. Blocking 과 Non-Blocking “node.js는 Single Thread, 동시작업을 Event Loop를 실행하여 처리”
  • 30. Blocking 과 Non-Blocking Event Loop? “헤이, probablyExpensiveFunction(), 니 일을 해줘. 하지만 나 Single Node.js 쓰레드는 네가 끝낼 때까지 여기서 기다리지 않을거 야. 네 아래에 있는 코드 라인을 계속 실행할거야. 그러니 여기 이 callbackFunction()을 가져가서 네가 너의 비싼 일을 모두 끝냈을 때 호출(callback)해 주겠니? 고마워!”
  • 31. Blocking 과 Non-Blocking HTTP서버 라우터 리턴(기다려!) 요청 핸들러 HTTP서버 response 객체를 넘김 라우터 response 객체를 넘김 요청 핸들러 요청 응답 전달 전달 리턴(기다려!) 요청 응답 요청 핸들러에서 응답을 처리하게
  • 32. Blocking 과 Non-Blocking // server.js 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(8888); console.log("Server has started."); } exports.start = start;
  • 33. Blocking 과 Non-Blocking // router.js 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;
  • 34. Blocking 과 Non-Blocking // requestHandlers.js function start(response) { console.log("Request handler 'start' was called."); // 비동기 Non-Blocking 함수를 사용. setTimeout(function(){ response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello Start"); response.end(); }, 10000); } function hello(response) { console.log("Request handler 'hello' was called."); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello Hello"); response.end(); } exports.start = start; exports.hello = hello;
  • 35. Blocking 과 Non-Blocking // terminal $ node index.js // 여러개 browser에서 동시에 http://localhost:8888/ http://localhost:8888/start http://localhost:8888/hello http://localhost:8888/something 해결! 하지만 큰 의미는 없으니 지웁시다.
  • 36. Blocking 과 Non-Blocking // requestHandlers.js function start(response) { console.log("Request handler 'start' was called.”); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello Start"); response.end(); } function hello(response) { console.log("Request handler 'hello' was called."); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello Hello"); response.end(); } exports.start = start; exports.hello = hello;
  • 37. Blocking 과 Non-Blocking 여기서 기억할 점. “Javascript엔 만나자마자 Event Loop에 넣고 다음줄로 넘어가는 함수가 있다.” (다 그런건 아니다.)
  • 38. 뷰 로직을 만들고 연동하기. 요청 HTTP서버 : 웹페이지 제공 라우터 : 요청과 요청을 처리할 핸들러들을 연결 요청 핸들러 : 요청을 만족시키기위한 핸들러 뷰 로직 : 브라우저로 콘텐트를 만들어 보내기 위한 로직 응답
  • 39. 뷰 로직을 만들고 연동하기. // requestHandlers.js function start(response) { console.log("Request handler 'start' was called."); var body = ‘<html>'+'<head>'+ '<meta http-equiv="Content-Type" content="text/html; '+ 'charset=UTF-8" />'+ '</head>'+ '<body>'+ '이름을 입력하세요.'+ '<br>'+ '<form action="/hello" method="post">'+ '<input type="text" name="text"></input>'+ '<input type="submit" value="입력" />'+ '</form>'+'</body>'+'</html>'; response.writeHead(200, {"Content-Type": "text/html"}); response.write(body); response.end(); }
  • 40. 뷰 로직을 만들고 연동하기. POST Data를 비동기로 받기. request.addListener("data", function(chunk) { // called when a new chunk of data was received }); request.addListener("end", function() { // called when all chunks of data have been received });
  • 41. 뷰 로직을 만들고 연동하기. POST Data를 비동기로 받기. // server.js 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(postDataChunk) { postData += postDataChunk; console.log("Received POST data chunk '"+ postDataChunk + "'."); }); request.addListener("end", function() { route(handle, pathname, response, postData); }); }
  • 42. 뷰 로직을 만들고 연동하기. POST Data를 비동기로 받기. // router.js 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(); } }
  • 43. 뷰 로직을 만들고 연동하기. POST Data를 받아서 사용하기. // requestHandlers.js function hello(response, postData) { console.log("Request handler 'hello' was called."); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("안녕하세요. "+ postData + "님"); response.end(); }
  • 44. 뷰 로직을 만들고 연동하기. POST Data를 받아서 사용하기. -> text만 가져오기. // requestHandlers.js var querystring = require("querystring"); // ... function hello(response, postData) { console.log("Request handler 'upload' was called."); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("안녕하세요. "+ querystring.parse(postData).text + "님"); response.end(); }
  • 45. 뷰 로직을 만들고 연동하기. // terminal $ node index.js // browser http://localhost:8888/ 완성!
  • 46. 공부하기 GET Method와 POST Method의 차이점 과제 같은 로직을 GET Method를 사용하여 만들어 보기.
  • 48.