SlideShare a Scribd company logo
1 of 38
Node.JS의 도입과 활용
2015. 7. 22
Jinwook Jeong
NodeJS
Node.JS 소개
자바스크립트의 특성은 다른 동적 언어 매우 다르다. 쓰레드에 대한 개념이 없다.
동기화 모델은 이벤트를 기반으로 하여 완전하다. Ryan Dahl
NodeJS
Node.JS 특징
• 이벤트 처리 I/O 프레임워크
– Chrome V8 자바스크립트 엔진 위에서 동작
– Single Thread 기반의 Event Loop에 기반한 비동기 I/O
NodeJS
Node.JS 도입의 이유
• 서버가 응답상태를 클라이언트에 알려준다면?
– 클라이언트가 서버에 쿼리를 날리지 않아도 비동기적 응답을 해줌
– Non Blocking I/O기반의 파일의 읽기, 쓰기
• 자바스크립트로 서버프로그래밍을 할 수 있다면?
– 프론트엔드 개발개발과 백엔드 개발을 단일언어 JS로 처리할 수 있음
Node.JS를 위한 Javascript
NodeJS
• Closure
- 함수내부 변수들을 추적하고 조작하기 위한 함수
- 함수는 function scope를 가지며, 함수외부에서 함수내부 정의를 참조할 수
없으며, JS는 중첩된 함수를 허용함
– 클로저 생성을 위한 함수 표현식
function maker(){
return function(){
}
};
function maker(){
var v=undefined;
return {
set:function(p){v=p;},
get:function(p){return p; },
type:function(p){return typeof v; }
};
}
Node.JS를 위한 Javascript
NodeJS
• Hoisting
– 마지막 선언을 끌어올리고(Hoisting) 할당 부분을 그 자리에 둔다.
– 호이스팅에 대한 시각적인 예
function f() {
{
var x=1;
var x=2;
}
}
function f() {
var x;
{
x=1;
x=2;
}
}
Node.JS를 위한 Javascript
NodeJS
• IIFE(immediately invoked function expression) 즉시실행함수
– 지역변수의 Block Scope 지원을 위한 방법
– 즉시실행함수의 예
function f(){
var v=0;
console.log(v); //0
for(var i=1,n=10;i<n;i++){
(function(){
var v=i;
console.log(v);//1-9
return v;
})();
}
console.log(v); //0,
}
Node.JS를 위한 Javascript
NodeJS
• Client J.S와 Node.JS의 차이점
– Node는 Google V8을 이용하며, ECMAScript 표준을 따름
– Javascript는 Browser version에 의존적
– Global 객체의 Priority
• Var localvar=myvalue; // Node.JS는 지역변수가 global 변수보다 우선이다.
– Node.JS에서는 Global variable을 global object로 사용하며, J.S에서는
Window variable을 global object로 사용함
• 브라우저 모드와 같이 처리
– GLOBAL.window = GLOBAL;
Node.JS 도입을 위한 장단점
NodeJS
• 장점
– 생산성
• Socket.IO 캡슐화, JS사용
• CRUD rest api 구현이 용이함
• Npm에 기반한 외부모듈 도입 용이
– Redis, Mongodb, mysql 등
• 단점
– Call Back Hell
• 이벤트 응답을 위해 함수가 중첩형태로 호출
– 가독성 저해 요인 (asynchronous 모듈 이용이 가능하나 완전 해결책은 아님)
– 유지보수의 어려움
• 특정 라인이 에러를 가지면 서버 자체가 다운됨
• 신속한 장애대응(Fast Troubleshooting)이 어렵다.
Node.JS 도입 – Node.JS 설치
NodeJS
yum -y groupinstall "Development Tools"
wget http://nodejs.org/dist/v0.10.17/node-v0.10.17.tar.gz
tar zxf node-v0.10.17.tar.gz
cd node-v0.10.17
./configure
make
make install
Node.JS 도입 – NPM
NodeJS
• NPM이란?
• Node Package Modules의 약자로, Node.JS 모듈의 저장소
• NPM의 사용이유
• core module인 http, file system, network, crypto 외에 필요한 모듈을 공급받음
• NPM 기본명령어 | $ npm install 패키지명
설치
| $ npm ls [모듈명]
설치된 모듈확인
| $ npm ls installed
설치된 모든모듈확인
| $ npm uninstall [모듈명]
모듈삭제
Node.JS 활용 – 모듈로딩
NodeJS
• Module 로딩의 일반적인 예
var http=require(‘http’),
util=require(‘util’),
fs=require(‘fs’);
Node.JS 활용 – 모듈로딩
NodeJS
• EJS 모듈로딩
// 모듈을 추출합니다.
var http = require('http');
var fs = require('fs');
var ejs = require('ejs');
// 서버를 생성하고 실행합니다.
http.createServer(function (request, response) {
fs.readFile('ejsPage.2.ejs', 'utf8', function (error, data) {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(ejs.render(data, {
name: 'RintIanTta',
description: 'Hello ejs With Node.js .. !'
}));
});
}).listen(52273, function () {
console.log('Server Running at http://127.0.0.1:52273');
});
Node.JS 활용 – HTTP Server
NodeJS
• 웹 서버
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello Worldn');
}).listen(8000);
console.log('Server running at http://localhost:8000/');
Node.JS 활용 – Socket.IO
NodeJS
var app =
require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading
index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function
(data) {
console.log(data);
});
});
| $ npm install socket.io <script
src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
Server (app.js) Client (index.html)
Using with HTTP Server
Node.JS 활용 – Socket.IO
NodeJS
// 모듈추출
var fs = require('fs');
// 서버생성
var server = require('http').createServer();
var io = require('socket.io').listen(server);
// 서버실행
server.listen(52273, function () {
console.log('Server Running at
http://127.0.0.1:52273');
});
// 이벤트를 연결합니다.
server.on('request', function (request, response) {
// 파일읽기
fs.readFile(‘test.html', function (error, data) {
response.writeHead(200,
{ 'Content-Type': 'text/html' });
response.end(data);
});
});
// 소켓 서버 이벤트 연결
io.sockets.on('connection', function (socket) {
// client socket에 대한 join 이벤트
socket.on('join', function (data) {
socket.join(data);
//소켓을 어떤룸에 join함
socket.set('room', data);
});
// message 이벤트
socket.on('message', function (data) {
socket.get('room', function (error, room) {
io.sockets.in(room).emit('message', data);
//or socket.broadcast.to(data).emit..
//to 생략의 경우 모두에게 보내짐
});
});
});
Node.JS 활용 – Socket.IO
NodeJS
..
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
window.onload = function () {
var room = prompt('방 이름을 입력하세요.', '');
var socket = io.connect();
socket.emit('join', room);
socket.on('message', function (data) {
$('<p>' + data + '</p>').appendTo('body');
});
document.getElementById('button').onclick = function () {
socket.emit('message', 'socket.io room message');
};
};
</script>
..
<button id="button">EMIT</button>
..
Node.JS 활용 – Express
NodeJS
• 특징
– 라우팅
– 세션 관리
– 탬플릿 엔진 (ejs, jade..)
– 기타 등등
• 설치
Express 설치 (4.0 기준)
| $ npm install -g express
| $ npm install -g express-generator
탬플릿엔진 설치
| $ npm install express jade
| $ npm install express ejs
프로젝트 생성
| $ express simpleweb
create : simpleweb
create : simpleweb/package.json
create : simpleweb/app.js
create : simpleweb/public
create : simpleweb/public/javascripts
create : simpleweb/public/images
create : simpleweb/routes
create : simpleweb/routes/index.js
create : simpleweb/routes/users.js
create : simpleweb/public/stylesheets
create : simpleweb/public/stylesheets/style.css
create : simpleweb/views
create : simpleweb/views/index.jade
create : simpleweb/views/layout.jade
create : simpleweb/views/error.jade
create : simpleweb/bin
create : simpleweb/bin/www
Express 프로젝트 생성
Node.JS 활용 – Express
NodeJS
• 탬플릿 엔진 비교
Node.JS 활용 – Express
NodeJS
• 간단한 라우팅
// 모듈을 추출합니다.
var http = require('http');
var express = require('express');
var app = express();
// 미들웨어를 설정합니다.
app.use(express.logger());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
// 라우터를 설정합니다.
app.get('/a', function (request, response) {
response.send('<a href="/b">Go to B</a>');
});
app.get('/b', function (request, response) {
response.send('<a href="/a">Go to A</a>');
});
// 서버를 실행합니다.
http.createServer(app).listen(52273, function () {
console.log('Server running at http://127.0.0.1:52273');
});
Node.JS 활용 – Express
NodeJS
• 라우팅시 정규식사용
• 라우팅 처리후 모듈별도 처리
app.get('/user/:id/:page[a-zA-Z]+’, function (request, response) {
response.send(‘Hello');
});
app.post('/login’,route.login);
exports.login=function(req,res){
}
Node.JS 활용 – RESTful Server
NodeJS
• RESTful Server
– 직관적인 URL을 이용한 HTTP기반의 SOAP의 대체기술
– POST, GET, PUT, DELETE라는 요청처리를 통해서 DB의 기본동작인 CRUD(Create,
Read, Update, Delete)를 처리가 가능
– REST는 비표준기술이면서, 웹서비스에 대한 개방형 기술임
– 요청은 명령(URL)과 요청타입(POST, GET)과 요청컨텐츠(POST 요청시)에 대하여
여러 형태(XML, JSON 등)로 응답할 수 있도록 설계
– Express 모듈을 이용하면 RESTful 서버 개발용이해짐
Node.JS 활용 – RESTful Server
NodeJS
• Express 기반의 Restful Server
// 모듈추출
var fs = require('fs');
var http = require('http');
var express = require('express');
var app = express();
// 미들웨어 설정
app.use(express.bodyParser());
app.use(app.router);
// 라우터 설정
app.get('/user', function (request, response) { });
app.get('/user/:id', function (request, response) { });
app.post('/user', function (request, response) { });
app.put('/user/:id', function (request, response) { });
app.del('/user/:id', function (request, response) { });
//서버실행
http.createServer(app).listen(52273, function () {
console.log('Server running at http://127.0.0.1:52273');
});
Node.JS 활용 – 비동기처리
NodeJS
• 비동기 로직
function getmember(user_id,callback){
if(user_id){
var data= ...
//callback함수 호출
callback(data);
}
write_log();
}
getmember(‘user’,function(param){
update(‘user’,param);
});
Node.JS 활용 – 비동기처리
NodeJS
• 비동기 로직 (callback hell...)
// 라우트를 수행합니다.
app.get('/', function (request, response) {
// 파일을 읽습니다.
fs.readFile('list.html', 'utf8', function (error, data) {
// 데이터베이스 쿼리를 실행합니다.
client.query('SELECT * FROM products', function (error, results) {
// 응답합니다.
response.send(ejs.render(data, {
data: results
}));
});
});
});
Node.JS 활용 – 비동기처리
NodeJS
• 비동기 로직으로의 변환 (nextTick 활용)
– nextTick으로 이벤트루프의 다음 차례까지로 연기함을 명시함
function Async(arg, cb){
if(arg){
process.nextTick(cb);
return;
}
fs.stat(‘file’,cb);
//파일정보 표시
//cb대신 익명함수 function(){} 로 대체가능
}
function foo() {
console.log('foo');
}
process.nextTick(foo);
console.log('bar');
//nextTick에 의해 foo는 이벤트 루프 처리가 완료된후 처리 (bar, foo 순으로 출력)
Node.JS 활용 – 비동기처리
NodeJS
• 비동기 로직으로의 변환 (nextTick 활용)
var client = net.connect(8124, function() {
console.log('client connected');
client.write('world!rn');
//동기적으로 실행되어, client가 초기화되기도 전에 콜백이 즉시 실행됨
});
function asyncFake(data, callback) {
if(data === 'foo') callback(true);
else callback(false);
}
asyncFake('bar', function(result) {
// 이 콜백은 실제로는 동기로 실행});
//항상 비동기가 되도록 정정
function asyncReal(data, callback) {
process.nextTick(function() {
callback(data === 'foo');
});
}
Node.JS 활용 – 비동기처리
NodeJS
• Async module(step)을 이용한 비동기 로직처리
Step(
function readSelf() {
fs.readFile(__filename, this);
},
function capitalize(err, text) {
if (err) throw err;
return text.toUpperCase();
},
function showIt(err, newText) {
if (err) throw err;
console.log(newText);
}
);
Node.JS 활용 – 모듈화
NodeJS
• 자바스크립트에서 모듈패턴
var myspace= (function(){
myprivate=function(){
return “this is myprivate”;
}
return {
mypublicvar:”hello”,
mypublic:function(){
return myprivate();
}
}
})();
Node.JS 활용 – 모듈화
NodeJS
• 자바스크립트에서 메소드 체이닝을 이용한 모듈정의
var Dbcon=function(){
this._host=‘’;
this._port=0;
}
Dbcon.prototype.host=function(host){
this._host=host;
};
Dbcon.prototype.port=function(port){
this._port=port;
};
Var conn=new Dbcon();
conn.host(‘localhost’);
conn.port(‘8080’);
Node.JS 활용 – 모듈화
NodeJS
• Node.JS에서의 메소드 체이닝을 이용한 모듈정의
module.exports=node;
function node() {};
node.prototype.index=function() {
}
node.prototype.test=function(){
}
function test2(){
}
Node.JS 활용 – 모듈화
NodeJS
• 공개 API 작성예
• 비공개 API 작성예
module.exports={
getMember:function(){
},
updateMember:function(){
}
}
function updateLog (){
console.log(‘update!’);
setInterval(
updateLog(),5000
);
}
Node.JS 활용 – MySQL
NodeJS
• MySQL
// 모듈을 추출합니다.
var mysql = require('mysql');
// 데이터베이스와 연결합니다.
var client = mysql.createConnection({
user: 'root',
password: '비밀번호',
database: 'Company'
});
// 데이터베이스 쿼리를 사용합니다.
client.query('SELECT * FROM products', function (error, result, fields) {
if (error) {
console.log('쿼리 문장에 오류가 있습니다.');
} else {
console.log(result);
}
});
Node.JS 활용 – MySQL
NodeJS
• MySQL ActiveRecord Module
– https://github.com/martintajur/node-mysql-activerecord
| $ npm install mysql-activerecord
var Db = require('mysql-activerecord');
var db = new Db.Adapter({
server: 'localhost',
username: 'root',
password: '12345',
database: 'test'
});
db.select("id, CONCAT(first_name, ' ', last_name) as full_name, email");
// This would produce: SELECT id, CONCAT(first_name, ' ', last_name) as full_name, email
…
var conditions = {
first_name: 'John',
last_name: 'Smith'
};
db.where(conditions);
// This would produce: … WHERE first_name = 'John' AND last_name = 'Smith' …
Node.JS 활용을 위한 Tip - Cluter
NodeJS
• Cluter의 사용이유
– 싱글코어에서 멀티코어 CPU를 이용할때 ‘Cluter’ 모듈을 이용함
var debug = require('debug')(‘구분이름');
var app = require('./system/app');
app.set('port', process.env.PORT || 3000);
var cluster = require('cluster');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
} else {
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
}
Node.JS 활용을 위한 Tip – Nodemon, Forever
NodeJS
| $ npm install -g nodemon
| $ npm install –g forever
운영시 서버를 백그라운드 형태로 실행가능
https://github.com/foreverjs/forever 사이트에 가면 해당 모듈 사용법이 나와 있음 그리고 아래와 같이 서버 실행.
forever [action] [options] SCRIPT [script-options]
위 형태대로 주요 명령어를 살펴보면 다음과 같음 ‘forever start server.js’
'forever list' 명령어 후에 인덱스 번호가 [0]이 있다면
‘forever stop 0’과 같은 형태로 백그라운드에서 실행되는 노드를 종료할 수 있음
개발시 활용할 수 있는 서버 재실행 모듈
https://github.com/remy/nodemon
‘nodemon ./server.js localhost 8080’ 명령어를 이용하여 실행
Nodemon
Forever
Node.JS 활용을 위한 Tip – 쓸만한 프레임워크
NodeJS
• Sails
– 라우팅을 MVC 형태로 구성이 가능함
• Koa.js
– 차세대 Express라고 불리우는 프레임워크
– 콜백 함수 또는 콜백 지옥을 차단하고 미들웨어의 예외처리를 강화함
var koa = require('koa');
var app = koa();
// x-response-time
app.use(function *(next){
var start = new Date;
yield next; //yield 컨텍스트로 next를 전달하고, 요청응답은 next에서 처리
var ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
});
Node.JS 활용을 위한 Tip – 기타 쓸만한 모듈
NodeJS
mocha : test framework (https://github.com/mochajs/mocha)
| $ npm install -g mocha
Primus : real-time frameworks (https://github.com/primus/primus)
| $ npm install -g nodemon
...

More Related Content

What's hot

Node.js + Websocket 삽질기
Node.js + Websocket 삽질기Node.js + Websocket 삽질기
Node.js + Websocket 삽질기Paprikhan
 
NODE.JS 글로벌 기업 적용 사례 그리고, real-time 어플리케이션 개발하기
NODE.JS 글로벌 기업 적용 사례  그리고, real-time 어플리케이션 개발하기NODE.JS 글로벌 기업 적용 사례  그리고, real-time 어플리케이션 개발하기
NODE.JS 글로벌 기업 적용 사례 그리고, real-time 어플리케이션 개발하기John Kim
 
Ryan Dahl의 Node.js 소개 동영상 해설 by doortts
Ryan Dahl의 Node.js 소개 동영상 해설 by doorttsRyan Dahl의 Node.js 소개 동영상 해설 by doortts
Ryan Dahl의 Node.js 소개 동영상 해설 by doorttsSuwon Chae
 
Python server-101
Python server-101Python server-101
Python server-101Huey Park
 
[C5]deview 2012 nodejs
[C5]deview 2012 nodejs[C5]deview 2012 nodejs
[C5]deview 2012 nodejsNAVER D2
 
Vert.x 세미나 이지원_배포용
Vert.x 세미나 이지원_배포용Vert.x 세미나 이지원_배포용
Vert.x 세미나 이지원_배포용지원 이
 
Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나JeongHun Byeon
 
소셜게임 서버 개발 관점에서 본 Node.js의 장단점과 대안
소셜게임 서버 개발 관점에서 본 Node.js의 장단점과 대안소셜게임 서버 개발 관점에서 본 Node.js의 장단점과 대안
소셜게임 서버 개발 관점에서 본 Node.js의 장단점과 대안Jeongsang Baek
 
Beejei node.js & web service
Beejei   node.js & web serviceBeejei   node.js & web service
Beejei node.js & web serviceBumjin Kim
 
vert.x 를 활용한 분산서버 개발하기
vert.x 를 활용한 분산서버 개발하기vert.x 를 활용한 분산서버 개발하기
vert.x 를 활용한 분산서버 개발하기John Kim
 
PHP를 위한 NginX(엔진엑스) 시작과 설정
PHP를 위한 NginX(엔진엑스) 시작과 설정PHP를 위한 NginX(엔진엑스) 시작과 설정
PHP를 위한 NginX(엔진엑스) 시작과 설정Jin wook
 
Vert.x
Vert.x Vert.x
Vert.x ymtech
 
진짜기초 Node.js
진짜기초 Node.js진짜기초 Node.js
진짜기초 Node.jsWoo Jin Kim
 
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기XpressEngine
 
Node.js 자바스크립트로 서버사이드 개발하기
Node.js 자바스크립트로 서버사이드 개발하기Node.js 자바스크립트로 서버사이드 개발하기
Node.js 자바스크립트로 서버사이드 개발하기JeongHun Byeon
 
스마트폰 앱 백-엔드 솔루션 개발을 위한 Node.js 실전 가이드
스마트폰 앱 백-엔드 솔루션 개발을 위한 Node.js 실전 가이드스마트폰 앱 백-엔드 솔루션 개발을 위한 Node.js 실전 가이드
스마트폰 앱 백-엔드 솔루션 개발을 위한 Node.js 실전 가이드Jeongsang Baek
 

What's hot (20)

Node.js + Websocket 삽질기
Node.js + Websocket 삽질기Node.js + Websocket 삽질기
Node.js + Websocket 삽질기
 
NODE.JS 글로벌 기업 적용 사례 그리고, real-time 어플리케이션 개발하기
NODE.JS 글로벌 기업 적용 사례  그리고, real-time 어플리케이션 개발하기NODE.JS 글로벌 기업 적용 사례  그리고, real-time 어플리케이션 개발하기
NODE.JS 글로벌 기업 적용 사례 그리고, real-time 어플리케이션 개발하기
 
Ryan Dahl의 Node.js 소개 동영상 해설 by doortts
Ryan Dahl의 Node.js 소개 동영상 해설 by doorttsRyan Dahl의 Node.js 소개 동영상 해설 by doortts
Ryan Dahl의 Node.js 소개 동영상 해설 by doortts
 
Python server-101
Python server-101Python server-101
Python server-101
 
[C5]deview 2012 nodejs
[C5]deview 2012 nodejs[C5]deview 2012 nodejs
[C5]deview 2012 nodejs
 
Vert.x 세미나 이지원_배포용
Vert.x 세미나 이지원_배포용Vert.x 세미나 이지원_배포용
Vert.x 세미나 이지원_배포용
 
Node.js 기본
Node.js 기본Node.js 기본
Node.js 기본
 
Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나Front-end Development Process - 어디까지 개선할 수 있나
Front-end Development Process - 어디까지 개선할 수 있나
 
소셜게임 서버 개발 관점에서 본 Node.js의 장단점과 대안
소셜게임 서버 개발 관점에서 본 Node.js의 장단점과 대안소셜게임 서버 개발 관점에서 본 Node.js의 장단점과 대안
소셜게임 서버 개발 관점에서 본 Node.js의 장단점과 대안
 
Node.js in Flitto
Node.js in FlittoNode.js in Flitto
Node.js in Flitto
 
Beejei node.js & web service
Beejei   node.js & web serviceBeejei   node.js & web service
Beejei node.js & web service
 
Node.js intro
Node.js introNode.js intro
Node.js intro
 
vert.x 를 활용한 분산서버 개발하기
vert.x 를 활용한 분산서버 개발하기vert.x 를 활용한 분산서버 개발하기
vert.x 를 활용한 분산서버 개발하기
 
PHP를 위한 NginX(엔진엑스) 시작과 설정
PHP를 위한 NginX(엔진엑스) 시작과 설정PHP를 위한 NginX(엔진엑스) 시작과 설정
PHP를 위한 NginX(엔진엑스) 시작과 설정
 
Vert.x
Vert.xVert.x
Vert.x
 
Vert.x
Vert.x Vert.x
Vert.x
 
진짜기초 Node.js
진짜기초 Node.js진짜기초 Node.js
진짜기초 Node.js
 
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
XECon2015 :: [2-2] 박상현 - React로 개발하는 SPA 실무 이야기
 
Node.js 자바스크립트로 서버사이드 개발하기
Node.js 자바스크립트로 서버사이드 개발하기Node.js 자바스크립트로 서버사이드 개발하기
Node.js 자바스크립트로 서버사이드 개발하기
 
스마트폰 앱 백-엔드 솔루션 개발을 위한 Node.js 실전 가이드
스마트폰 앱 백-엔드 솔루션 개발을 위한 Node.js 실전 가이드스마트폰 앱 백-엔드 솔루션 개발을 위한 Node.js 실전 가이드
스마트폰 앱 백-엔드 솔루션 개발을 위한 Node.js 실전 가이드
 

Similar to Node.js의 도입과 활용

빠르게훓어보는 Node.js와 Vert.x
빠르게훓어보는 Node.js와 Vert.x빠르게훓어보는 Node.js와 Vert.x
빠르게훓어보는 Node.js와 Vert.xTerry Cho
 
Nodejs, PhantomJS, casperJs, YSlow, expressjs
Nodejs, PhantomJS, casperJs, YSlow, expressjsNodejs, PhantomJS, casperJs, YSlow, expressjs
Nodejs, PhantomJS, casperJs, YSlow, expressjs기동 이
 
[IoT] MAKE with Open H/W + Node.JS - 3rd
[IoT] MAKE with Open H/W + Node.JS - 3rd[IoT] MAKE with Open H/W + Node.JS - 3rd
[IoT] MAKE with Open H/W + Node.JS - 3rdPark Jonggun
 
Node.js 팀 스터디 발표자료.
Node.js 팀 스터디 발표자료.Node.js 팀 스터디 발표자료.
Node.js 팀 스터디 발표자료.SeungWoo Lee
 
Nodejs발표자료 - 팀 세미나용
Nodejs발표자료 - 팀 세미나용 Nodejs발표자료 - 팀 세미나용
Nodejs발표자료 - 팀 세미나용 SuHyun Jeon
 
Internship backend
Internship backendInternship backend
Internship backendYein Sim
 
Startup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JSStartup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JSCirculus
 
Jenkins를 활용한 javascript 개발
Jenkins를 활용한 javascript 개발Jenkins를 활용한 javascript 개발
Jenkins를 활용한 javascript 개발지수 윤
 
[Korea Linux Forum] Implementing web based online multiplayer tetris with Ope...
[Korea Linux Forum] Implementing web based online multiplayer tetris with Ope...[Korea Linux Forum] Implementing web based online multiplayer tetris with Ope...
[Korea Linux Forum] Implementing web based online multiplayer tetris with Ope...JinKwon Lee
 
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기현철 조
 
Node.js 20버전에 변경된 점들.pdf
Node.js 20버전에 변경된 점들.pdfNode.js 20버전에 변경된 점들.pdf
Node.js 20버전에 변경된 점들.pdfSeung kyoo Park
 
Node.js 살펴보기
Node.js 살펴보기Node.js 살펴보기
Node.js 살펴보기명신 김
 
JCO 11th 클라우드 환경에서 Java EE 운영 환경 구축하기
JCO 11th 클라우드 환경에서 Java EE 운영 환경 구축하기JCO 11th 클라우드 환경에서 Java EE 운영 환경 구축하기
JCO 11th 클라우드 환경에서 Java EE 운영 환경 구축하기Ted Won
 
Tensorflow service & Machine Learning
Tensorflow service & Machine LearningTensorflow service & Machine Learning
Tensorflow service & Machine LearningJEEHYUN PAIK
 
모바일 게임과 앱을 위한 오픈소스 게임서버 엔진 프로젝트 CloudBread 프로젝트
모바일 게임과 앱을 위한 오픈소스 게임서버 엔진 프로젝트 CloudBread 프로젝트모바일 게임과 앱을 위한 오픈소스 게임서버 엔진 프로젝트 CloudBread 프로젝트
모바일 게임과 앱을 위한 오픈소스 게임서버 엔진 프로젝트 CloudBread 프로젝트Dae Kim
 

Similar to Node.js의 도입과 활용 (20)

빠르게훓어보는 Node.js와 Vert.x
빠르게훓어보는 Node.js와 Vert.x빠르게훓어보는 Node.js와 Vert.x
빠르게훓어보는 Node.js와 Vert.x
 
Nodejs, PhantomJS, casperJs, YSlow, expressjs
Nodejs, PhantomJS, casperJs, YSlow, expressjsNodejs, PhantomJS, casperJs, YSlow, expressjs
Nodejs, PhantomJS, casperJs, YSlow, expressjs
 
[IoT] MAKE with Open H/W + Node.JS - 3rd
[IoT] MAKE with Open H/W + Node.JS - 3rd[IoT] MAKE with Open H/W + Node.JS - 3rd
[IoT] MAKE with Open H/W + Node.JS - 3rd
 
Node.js 팀 스터디 발표자료.
Node.js 팀 스터디 발표자료.Node.js 팀 스터디 발표자료.
Node.js 팀 스터디 발표자료.
 
Node.js 첫걸음
Node.js 첫걸음Node.js 첫걸음
Node.js 첫걸음
 
Nodejs발표자료 - 팀 세미나용
Nodejs발표자료 - 팀 세미나용 Nodejs발표자료 - 팀 세미나용
Nodejs발표자료 - 팀 세미나용
 
Internship backend
Internship backendInternship backend
Internship backend
 
One-day-codelab
One-day-codelabOne-day-codelab
One-day-codelab
 
4-3. jquery
4-3. jquery4-3. jquery
4-3. jquery
 
Startup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JSStartup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JS
 
Jenkins를 활용한 javascript 개발
Jenkins를 활용한 javascript 개발Jenkins를 활용한 javascript 개발
Jenkins를 활용한 javascript 개발
 
[Korea Linux Forum] Implementing web based online multiplayer tetris with Ope...
[Korea Linux Forum] Implementing web based online multiplayer tetris with Ope...[Korea Linux Forum] Implementing web based online multiplayer tetris with Ope...
[Korea Linux Forum] Implementing web based online multiplayer tetris with Ope...
 
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
[NDC17] Unreal.js - 자바스크립트로 쉽고 빠른 UE4 개발하기
 
Node.js 20버전에 변경된 점들.pdf
Node.js 20버전에 변경된 점들.pdfNode.js 20버전에 변경된 점들.pdf
Node.js 20버전에 변경된 점들.pdf
 
Node.js 살펴보기
Node.js 살펴보기Node.js 살펴보기
Node.js 살펴보기
 
Nest js 101
Nest js 101Nest js 101
Nest js 101
 
요즘웹개발
요즘웹개발요즘웹개발
요즘웹개발
 
JCO 11th 클라우드 환경에서 Java EE 운영 환경 구축하기
JCO 11th 클라우드 환경에서 Java EE 운영 환경 구축하기JCO 11th 클라우드 환경에서 Java EE 운영 환경 구축하기
JCO 11th 클라우드 환경에서 Java EE 운영 환경 구축하기
 
Tensorflow service & Machine Learning
Tensorflow service & Machine LearningTensorflow service & Machine Learning
Tensorflow service & Machine Learning
 
모바일 게임과 앱을 위한 오픈소스 게임서버 엔진 프로젝트 CloudBread 프로젝트
모바일 게임과 앱을 위한 오픈소스 게임서버 엔진 프로젝트 CloudBread 프로젝트모바일 게임과 앱을 위한 오픈소스 게임서버 엔진 프로젝트 CloudBread 프로젝트
모바일 게임과 앱을 위한 오픈소스 게임서버 엔진 프로젝트 CloudBread 프로젝트
 

More from Jin wook

자연어처리 소개
자연어처리 소개자연어처리 소개
자연어처리 소개Jin wook
 
클린 아키텍처 재해석
클린 아키텍처 재해석클린 아키텍처 재해석
클린 아키텍처 재해석Jin wook
 
Angular2를 위한 컴포넌트 분석과 개발
Angular2를 위한 컴포넌트 분석과 개발Angular2를 위한 컴포넌트 분석과 개발
Angular2를 위한 컴포넌트 분석과 개발Jin wook
 
Angular2를 위한 타입스크립트
Angular2를 위한 타입스크립트Angular2를 위한 타입스크립트
Angular2를 위한 타입스크립트Jin wook
 
Angular2를 활용한 컴포넌트 중심의 개발
Angular2를 활용한 컴포넌트 중심의 개발Angular2를 활용한 컴포넌트 중심의 개발
Angular2를 활용한 컴포넌트 중심의 개발Jin wook
 
MIPS CPU의 이해 (입문)
MIPS CPU의 이해 (입문)MIPS CPU의 이해 (입문)
MIPS CPU의 이해 (입문)Jin wook
 
Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략Jin wook
 
Mongo DB로 진행하는 CRUD
Mongo DB로 진행하는 CRUDMongo DB로 진행하는 CRUD
Mongo DB로 진행하는 CRUDJin wook
 
아파치 쓰리프트 (Apache Thrift)
아파치 쓰리프트 (Apache Thrift) 아파치 쓰리프트 (Apache Thrift)
아파치 쓰리프트 (Apache Thrift) Jin wook
 
파이썬(Python) 소개
파이썬(Python) 소개파이썬(Python) 소개
파이썬(Python) 소개Jin wook
 
빅 데이터 개요 및 활용
빅 데이터 개요 및 활용빅 데이터 개요 및 활용
빅 데이터 개요 및 활용Jin wook
 
AngularJS의 개발방식에 대하여
AngularJS의 개발방식에 대하여AngularJS의 개발방식에 대하여
AngularJS의 개발방식에 대하여Jin wook
 

More from Jin wook (12)

자연어처리 소개
자연어처리 소개자연어처리 소개
자연어처리 소개
 
클린 아키텍처 재해석
클린 아키텍처 재해석클린 아키텍처 재해석
클린 아키텍처 재해석
 
Angular2를 위한 컴포넌트 분석과 개발
Angular2를 위한 컴포넌트 분석과 개발Angular2를 위한 컴포넌트 분석과 개발
Angular2를 위한 컴포넌트 분석과 개발
 
Angular2를 위한 타입스크립트
Angular2를 위한 타입스크립트Angular2를 위한 타입스크립트
Angular2를 위한 타입스크립트
 
Angular2를 활용한 컴포넌트 중심의 개발
Angular2를 활용한 컴포넌트 중심의 개발Angular2를 활용한 컴포넌트 중심의 개발
Angular2를 활용한 컴포넌트 중심의 개발
 
MIPS CPU의 이해 (입문)
MIPS CPU의 이해 (입문)MIPS CPU의 이해 (입문)
MIPS CPU의 이해 (입문)
 
Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략Mongo DB 성능최적화 전략
Mongo DB 성능최적화 전략
 
Mongo DB로 진행하는 CRUD
Mongo DB로 진행하는 CRUDMongo DB로 진행하는 CRUD
Mongo DB로 진행하는 CRUD
 
아파치 쓰리프트 (Apache Thrift)
아파치 쓰리프트 (Apache Thrift) 아파치 쓰리프트 (Apache Thrift)
아파치 쓰리프트 (Apache Thrift)
 
파이썬(Python) 소개
파이썬(Python) 소개파이썬(Python) 소개
파이썬(Python) 소개
 
빅 데이터 개요 및 활용
빅 데이터 개요 및 활용빅 데이터 개요 및 활용
빅 데이터 개요 및 활용
 
AngularJS의 개발방식에 대하여
AngularJS의 개발방식에 대하여AngularJS의 개발방식에 대하여
AngularJS의 개발방식에 대하여
 

Node.js의 도입과 활용

  • 1. Node.JS의 도입과 활용 2015. 7. 22 Jinwook Jeong
  • 2. NodeJS Node.JS 소개 자바스크립트의 특성은 다른 동적 언어 매우 다르다. 쓰레드에 대한 개념이 없다. 동기화 모델은 이벤트를 기반으로 하여 완전하다. Ryan Dahl
  • 3. NodeJS Node.JS 특징 • 이벤트 처리 I/O 프레임워크 – Chrome V8 자바스크립트 엔진 위에서 동작 – Single Thread 기반의 Event Loop에 기반한 비동기 I/O
  • 4. NodeJS Node.JS 도입의 이유 • 서버가 응답상태를 클라이언트에 알려준다면? – 클라이언트가 서버에 쿼리를 날리지 않아도 비동기적 응답을 해줌 – Non Blocking I/O기반의 파일의 읽기, 쓰기 • 자바스크립트로 서버프로그래밍을 할 수 있다면? – 프론트엔드 개발개발과 백엔드 개발을 단일언어 JS로 처리할 수 있음
  • 5. Node.JS를 위한 Javascript NodeJS • Closure - 함수내부 변수들을 추적하고 조작하기 위한 함수 - 함수는 function scope를 가지며, 함수외부에서 함수내부 정의를 참조할 수 없으며, JS는 중첩된 함수를 허용함 – 클로저 생성을 위한 함수 표현식 function maker(){ return function(){ } }; function maker(){ var v=undefined; return { set:function(p){v=p;}, get:function(p){return p; }, type:function(p){return typeof v; } }; }
  • 6. Node.JS를 위한 Javascript NodeJS • Hoisting – 마지막 선언을 끌어올리고(Hoisting) 할당 부분을 그 자리에 둔다. – 호이스팅에 대한 시각적인 예 function f() { { var x=1; var x=2; } } function f() { var x; { x=1; x=2; } }
  • 7. Node.JS를 위한 Javascript NodeJS • IIFE(immediately invoked function expression) 즉시실행함수 – 지역변수의 Block Scope 지원을 위한 방법 – 즉시실행함수의 예 function f(){ var v=0; console.log(v); //0 for(var i=1,n=10;i<n;i++){ (function(){ var v=i; console.log(v);//1-9 return v; })(); } console.log(v); //0, }
  • 8. Node.JS를 위한 Javascript NodeJS • Client J.S와 Node.JS의 차이점 – Node는 Google V8을 이용하며, ECMAScript 표준을 따름 – Javascript는 Browser version에 의존적 – Global 객체의 Priority • Var localvar=myvalue; // Node.JS는 지역변수가 global 변수보다 우선이다. – Node.JS에서는 Global variable을 global object로 사용하며, J.S에서는 Window variable을 global object로 사용함 • 브라우저 모드와 같이 처리 – GLOBAL.window = GLOBAL;
  • 9. Node.JS 도입을 위한 장단점 NodeJS • 장점 – 생산성 • Socket.IO 캡슐화, JS사용 • CRUD rest api 구현이 용이함 • Npm에 기반한 외부모듈 도입 용이 – Redis, Mongodb, mysql 등 • 단점 – Call Back Hell • 이벤트 응답을 위해 함수가 중첩형태로 호출 – 가독성 저해 요인 (asynchronous 모듈 이용이 가능하나 완전 해결책은 아님) – 유지보수의 어려움 • 특정 라인이 에러를 가지면 서버 자체가 다운됨 • 신속한 장애대응(Fast Troubleshooting)이 어렵다.
  • 10. Node.JS 도입 – Node.JS 설치 NodeJS yum -y groupinstall "Development Tools" wget http://nodejs.org/dist/v0.10.17/node-v0.10.17.tar.gz tar zxf node-v0.10.17.tar.gz cd node-v0.10.17 ./configure make make install
  • 11. Node.JS 도입 – NPM NodeJS • NPM이란? • Node Package Modules의 약자로, Node.JS 모듈의 저장소 • NPM의 사용이유 • core module인 http, file system, network, crypto 외에 필요한 모듈을 공급받음 • NPM 기본명령어 | $ npm install 패키지명 설치 | $ npm ls [모듈명] 설치된 모듈확인 | $ npm ls installed 설치된 모든모듈확인 | $ npm uninstall [모듈명] 모듈삭제
  • 12. Node.JS 활용 – 모듈로딩 NodeJS • Module 로딩의 일반적인 예 var http=require(‘http’), util=require(‘util’), fs=require(‘fs’);
  • 13. Node.JS 활용 – 모듈로딩 NodeJS • EJS 모듈로딩 // 모듈을 추출합니다. var http = require('http'); var fs = require('fs'); var ejs = require('ejs'); // 서버를 생성하고 실행합니다. http.createServer(function (request, response) { fs.readFile('ejsPage.2.ejs', 'utf8', function (error, data) { response.writeHead(200, { 'Content-Type': 'text/html' }); response.end(ejs.render(data, { name: 'RintIanTta', description: 'Hello ejs With Node.js .. !' })); }); }).listen(52273, function () { console.log('Server Running at http://127.0.0.1:52273'); });
  • 14. Node.JS 활용 – HTTP Server NodeJS • 웹 서버 var http = require('http'); http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello Worldn'); }).listen(8000); console.log('Server running at http://localhost:8000/');
  • 15. Node.JS 활용 – Socket.IO NodeJS var app = require('http').createServer(handler) var io = require('socket.io')(app); var fs = require('fs'); app.listen(80); function handler (req, res) { fs.readFile(__dirname + '/index.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); res.end(data); }); } io.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); }); | $ npm install socket.io <script src="/socket.io/socket.io.js"></script> <script> var socket = io('http://localhost'); socket.on('news', function (data) { console.log(data); socket.emit('my other event', { my: 'data' }); }); </script> Server (app.js) Client (index.html) Using with HTTP Server
  • 16. Node.JS 활용 – Socket.IO NodeJS // 모듈추출 var fs = require('fs'); // 서버생성 var server = require('http').createServer(); var io = require('socket.io').listen(server); // 서버실행 server.listen(52273, function () { console.log('Server Running at http://127.0.0.1:52273'); }); // 이벤트를 연결합니다. server.on('request', function (request, response) { // 파일읽기 fs.readFile(‘test.html', function (error, data) { response.writeHead(200, { 'Content-Type': 'text/html' }); response.end(data); }); }); // 소켓 서버 이벤트 연결 io.sockets.on('connection', function (socket) { // client socket에 대한 join 이벤트 socket.on('join', function (data) { socket.join(data); //소켓을 어떤룸에 join함 socket.set('room', data); }); // message 이벤트 socket.on('message', function (data) { socket.get('room', function (error, room) { io.sockets.in(room).emit('message', data); //or socket.broadcast.to(data).emit.. //to 생략의 경우 모두에게 보내짐 }); }); });
  • 17. Node.JS 활용 – Socket.IO NodeJS .. <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="/socket.io/socket.io.js"></script> <script> window.onload = function () { var room = prompt('방 이름을 입력하세요.', ''); var socket = io.connect(); socket.emit('join', room); socket.on('message', function (data) { $('<p>' + data + '</p>').appendTo('body'); }); document.getElementById('button').onclick = function () { socket.emit('message', 'socket.io room message'); }; }; </script> .. <button id="button">EMIT</button> ..
  • 18. Node.JS 활용 – Express NodeJS • 특징 – 라우팅 – 세션 관리 – 탬플릿 엔진 (ejs, jade..) – 기타 등등 • 설치 Express 설치 (4.0 기준) | $ npm install -g express | $ npm install -g express-generator 탬플릿엔진 설치 | $ npm install express jade | $ npm install express ejs 프로젝트 생성 | $ express simpleweb create : simpleweb create : simpleweb/package.json create : simpleweb/app.js create : simpleweb/public create : simpleweb/public/javascripts create : simpleweb/public/images create : simpleweb/routes create : simpleweb/routes/index.js create : simpleweb/routes/users.js create : simpleweb/public/stylesheets create : simpleweb/public/stylesheets/style.css create : simpleweb/views create : simpleweb/views/index.jade create : simpleweb/views/layout.jade create : simpleweb/views/error.jade create : simpleweb/bin create : simpleweb/bin/www Express 프로젝트 생성
  • 19. Node.JS 활용 – Express NodeJS • 탬플릿 엔진 비교
  • 20. Node.JS 활용 – Express NodeJS • 간단한 라우팅 // 모듈을 추출합니다. var http = require('http'); var express = require('express'); var app = express(); // 미들웨어를 설정합니다. app.use(express.logger()); app.use(app.router); app.use(express.static(__dirname + '/public')); // 라우터를 설정합니다. app.get('/a', function (request, response) { response.send('<a href="/b">Go to B</a>'); }); app.get('/b', function (request, response) { response.send('<a href="/a">Go to A</a>'); }); // 서버를 실행합니다. http.createServer(app).listen(52273, function () { console.log('Server running at http://127.0.0.1:52273'); });
  • 21. Node.JS 활용 – Express NodeJS • 라우팅시 정규식사용 • 라우팅 처리후 모듈별도 처리 app.get('/user/:id/:page[a-zA-Z]+’, function (request, response) { response.send(‘Hello'); }); app.post('/login’,route.login); exports.login=function(req,res){ }
  • 22. Node.JS 활용 – RESTful Server NodeJS • RESTful Server – 직관적인 URL을 이용한 HTTP기반의 SOAP의 대체기술 – POST, GET, PUT, DELETE라는 요청처리를 통해서 DB의 기본동작인 CRUD(Create, Read, Update, Delete)를 처리가 가능 – REST는 비표준기술이면서, 웹서비스에 대한 개방형 기술임 – 요청은 명령(URL)과 요청타입(POST, GET)과 요청컨텐츠(POST 요청시)에 대하여 여러 형태(XML, JSON 등)로 응답할 수 있도록 설계 – Express 모듈을 이용하면 RESTful 서버 개발용이해짐
  • 23. Node.JS 활용 – RESTful Server NodeJS • Express 기반의 Restful Server // 모듈추출 var fs = require('fs'); var http = require('http'); var express = require('express'); var app = express(); // 미들웨어 설정 app.use(express.bodyParser()); app.use(app.router); // 라우터 설정 app.get('/user', function (request, response) { }); app.get('/user/:id', function (request, response) { }); app.post('/user', function (request, response) { }); app.put('/user/:id', function (request, response) { }); app.del('/user/:id', function (request, response) { }); //서버실행 http.createServer(app).listen(52273, function () { console.log('Server running at http://127.0.0.1:52273'); });
  • 24. Node.JS 활용 – 비동기처리 NodeJS • 비동기 로직 function getmember(user_id,callback){ if(user_id){ var data= ... //callback함수 호출 callback(data); } write_log(); } getmember(‘user’,function(param){ update(‘user’,param); });
  • 25. Node.JS 활용 – 비동기처리 NodeJS • 비동기 로직 (callback hell...) // 라우트를 수행합니다. app.get('/', function (request, response) { // 파일을 읽습니다. fs.readFile('list.html', 'utf8', function (error, data) { // 데이터베이스 쿼리를 실행합니다. client.query('SELECT * FROM products', function (error, results) { // 응답합니다. response.send(ejs.render(data, { data: results })); }); }); });
  • 26. Node.JS 활용 – 비동기처리 NodeJS • 비동기 로직으로의 변환 (nextTick 활용) – nextTick으로 이벤트루프의 다음 차례까지로 연기함을 명시함 function Async(arg, cb){ if(arg){ process.nextTick(cb); return; } fs.stat(‘file’,cb); //파일정보 표시 //cb대신 익명함수 function(){} 로 대체가능 } function foo() { console.log('foo'); } process.nextTick(foo); console.log('bar'); //nextTick에 의해 foo는 이벤트 루프 처리가 완료된후 처리 (bar, foo 순으로 출력)
  • 27. Node.JS 활용 – 비동기처리 NodeJS • 비동기 로직으로의 변환 (nextTick 활용) var client = net.connect(8124, function() { console.log('client connected'); client.write('world!rn'); //동기적으로 실행되어, client가 초기화되기도 전에 콜백이 즉시 실행됨 }); function asyncFake(data, callback) { if(data === 'foo') callback(true); else callback(false); } asyncFake('bar', function(result) { // 이 콜백은 실제로는 동기로 실행}); //항상 비동기가 되도록 정정 function asyncReal(data, callback) { process.nextTick(function() { callback(data === 'foo'); }); }
  • 28. Node.JS 활용 – 비동기처리 NodeJS • Async module(step)을 이용한 비동기 로직처리 Step( function readSelf() { fs.readFile(__filename, this); }, function capitalize(err, text) { if (err) throw err; return text.toUpperCase(); }, function showIt(err, newText) { if (err) throw err; console.log(newText); } );
  • 29. Node.JS 활용 – 모듈화 NodeJS • 자바스크립트에서 모듈패턴 var myspace= (function(){ myprivate=function(){ return “this is myprivate”; } return { mypublicvar:”hello”, mypublic:function(){ return myprivate(); } } })();
  • 30. Node.JS 활용 – 모듈화 NodeJS • 자바스크립트에서 메소드 체이닝을 이용한 모듈정의 var Dbcon=function(){ this._host=‘’; this._port=0; } Dbcon.prototype.host=function(host){ this._host=host; }; Dbcon.prototype.port=function(port){ this._port=port; }; Var conn=new Dbcon(); conn.host(‘localhost’); conn.port(‘8080’);
  • 31. Node.JS 활용 – 모듈화 NodeJS • Node.JS에서의 메소드 체이닝을 이용한 모듈정의 module.exports=node; function node() {}; node.prototype.index=function() { } node.prototype.test=function(){ } function test2(){ }
  • 32. Node.JS 활용 – 모듈화 NodeJS • 공개 API 작성예 • 비공개 API 작성예 module.exports={ getMember:function(){ }, updateMember:function(){ } } function updateLog (){ console.log(‘update!’); setInterval( updateLog(),5000 ); }
  • 33. Node.JS 활용 – MySQL NodeJS • MySQL // 모듈을 추출합니다. var mysql = require('mysql'); // 데이터베이스와 연결합니다. var client = mysql.createConnection({ user: 'root', password: '비밀번호', database: 'Company' }); // 데이터베이스 쿼리를 사용합니다. client.query('SELECT * FROM products', function (error, result, fields) { if (error) { console.log('쿼리 문장에 오류가 있습니다.'); } else { console.log(result); } });
  • 34. Node.JS 활용 – MySQL NodeJS • MySQL ActiveRecord Module – https://github.com/martintajur/node-mysql-activerecord | $ npm install mysql-activerecord var Db = require('mysql-activerecord'); var db = new Db.Adapter({ server: 'localhost', username: 'root', password: '12345', database: 'test' }); db.select("id, CONCAT(first_name, ' ', last_name) as full_name, email"); // This would produce: SELECT id, CONCAT(first_name, ' ', last_name) as full_name, email … var conditions = { first_name: 'John', last_name: 'Smith' }; db.where(conditions); // This would produce: … WHERE first_name = 'John' AND last_name = 'Smith' …
  • 35. Node.JS 활용을 위한 Tip - Cluter NodeJS • Cluter의 사용이유 – 싱글코어에서 멀티코어 CPU를 이용할때 ‘Cluter’ 모듈을 이용함 var debug = require('debug')(‘구분이름'); var app = require('./system/app'); app.set('port', process.env.PORT || 3000); var cluster = require('cluster'); var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', function(worker, code, signal) { console.log('worker ' + worker.process.pid + ' died'); }); } else { var server = app.listen(app.get('port'), function() { debug('Express server listening on port ' + server.address().port); }); }
  • 36. Node.JS 활용을 위한 Tip – Nodemon, Forever NodeJS | $ npm install -g nodemon | $ npm install –g forever 운영시 서버를 백그라운드 형태로 실행가능 https://github.com/foreverjs/forever 사이트에 가면 해당 모듈 사용법이 나와 있음 그리고 아래와 같이 서버 실행. forever [action] [options] SCRIPT [script-options] 위 형태대로 주요 명령어를 살펴보면 다음과 같음 ‘forever start server.js’ 'forever list' 명령어 후에 인덱스 번호가 [0]이 있다면 ‘forever stop 0’과 같은 형태로 백그라운드에서 실행되는 노드를 종료할 수 있음 개발시 활용할 수 있는 서버 재실행 모듈 https://github.com/remy/nodemon ‘nodemon ./server.js localhost 8080’ 명령어를 이용하여 실행 Nodemon Forever
  • 37. Node.JS 활용을 위한 Tip – 쓸만한 프레임워크 NodeJS • Sails – 라우팅을 MVC 형태로 구성이 가능함 • Koa.js – 차세대 Express라고 불리우는 프레임워크 – 콜백 함수 또는 콜백 지옥을 차단하고 미들웨어의 예외처리를 강화함 var koa = require('koa'); var app = koa(); // x-response-time app.use(function *(next){ var start = new Date; yield next; //yield 컨텍스트로 next를 전달하고, 요청응답은 next에서 처리 var ms = new Date - start; this.set('X-Response-Time', ms + 'ms'); });
  • 38. Node.JS 활용을 위한 Tip – 기타 쓸만한 모듈 NodeJS mocha : test framework (https://github.com/mochajs/mocha) | $ npm install -g mocha Primus : real-time frameworks (https://github.com/primus/primus) | $ npm install -g nodemon ...

Editor's Notes

  1. - 클로저는 실행유효 범위를 가르키며, 중첩구조의 형태를 가지는 유효범위 함수를 생성하는것이다. - 함수 외부에서 함수 내부 변수 참조를 위한 예제이며 익명형과 이름형에 대한 예시임
  2. 마지막 선언이 특정 값이 아닌 함수가 될 수 도 있음 호이스팅 되면 이벤트 기반 처리시 영향을 가짐
  3. 즉시실행함수안에서는 break; continue를 사용할 수 없음
  4. sudo passwd root 암호 변경후 su root 로 실행
  5. Emit 과 On에 대한 차이점에 대한 구분이 필요함 이벤트 보내기(emitting)은 두가지중 하나를 쓸 수 있음 socket.broadcast.to('room') or io.sockets.in('room')
  6. 20140617 www 파일을 가지고 서버를 실행할 수 있음 20140718 Ejs, jade와 관련하여 아래 의존모듈을 추가설치할 수 있음 Debug, static-favicon, morgan, cookie-parser, body-parser 20140724 EJS 좋은예제 http://superbigtree.tumblr.com/post/62759231807/a-simple-example-application-using-express-ejs-and​
  7. 20140826 http://paularmstrong.github.io/node-templates/index.html
  8. App.use는 미들웨어 구동전 사전 작업을 할 수 있는 API
  9. http://blog.outsider.ne.kr/739
  10. 20140707
  11. 20141010
  12. root 계정으로 변경후 설치 -g 옵션을 통해 전역으로 설치
  13. Yield next; Next라는 파라미터를 yield 컨텍스트로 전달함으로서, 요청에 대한 응답은 next에서 처리하도록 함. 콜백까지 수행한후에, 시간값을 표시함
  14. 20140723