nodejs, phantomjs, casperjs, yslow, expressjs

34
Node.js 발발발 발발발

Upload: -

Post on 17-Nov-2014

563 views

Category:

Software


0 download

DESCRIPTION

node.js 관련 기초 세미나 자료.

TRANSCRIPT

Page 1: Nodejs, PhantomJS, casperJs, YSlow, expressjs

Node.js

발표자 이기동

Page 2: Nodejs, PhantomJS, casperJs, YSlow, expressjs

Node.js?• 라이언 달이 2009 년 JSConf 에서 발표

• 서버사이드 자바스크립트 (V8 엔진 ) 프레임워크

• 이벤트 기반 (Event Driven) Non-Blocking I/O 방식

• 버전 (2014-5-26 기준 ) : v0.10.28

• C++ Complie

• 단일 쓰레드 이벤트 루프로 구동

Page 3: Nodejs, PhantomJS, casperJs, YSlow, expressjs

장점 ?• 가볍고

• 빠르다

• 설치와 사용이 간편하다

• 많은 모듈 (npmjs.org 2014-05-26 기준 : 75,038 개 )

• Front-End 개발자의 진입이 쉽다 .

Page 4: Nodejs, PhantomJS, casperJs, YSlow, expressjs

단점 ?• Event-Driven 프로그래밍이 쉽지 않다 .

• 동기적 코드가 전체 성능 저하를 유발한다 .

• CPU 작업이 많은 곳에는 적합하지 않다 .

• 에러 발생시 서버가 종료될 수 있다 ..

Page 5: Nodejs, PhantomJS, casperJs, YSlow, expressjs

어디서 쓰고 있지 ?

Page 6: Nodejs, PhantomJS, casperJs, YSlow, expressjs

Node.js 처리구조 ?

1. 피자를 전화로 주문한다 . (Callback 함수전달 )

2. 다른 일을 한다 .

3. 피자 배달이 오면 (EVENT),

결제하고 먹는다 (Callback 함수 내용 실행 ).

1. 피자를 테이크아웃 주문한다 .

2. 될때까지 기다린다 .(cpu Wait)

3. 완료되면 결제 후 먹는다 .

싱글 스레드 기반 비동기 처리 멀티 스레드 기반 동기 처리

Page 7: Nodejs, PhantomJS, casperJs, YSlow, expressjs

설치• http://nodejs.org/download/ 각 OS 별로 다운로드

# 의존 패키지 설치 ( 레드헷 계열 )yum install gcc gcc-c++yum install openssl-develyum install make

# 다운로드 및 설치cd /usr/src && wget http://nodejs.org/dist/v0.10.28/node-v0.10.28.tar.gztar zxvf node-v0.10.28.tar.gzcd node-v0.10.28./configuremake && make install

Page 8: Nodejs, PhantomJS, casperJs, YSlow, expressjs

실행

> node testApp.js또는

#!/usr/local/bin/node 1 라인에 추가chmod a+x ./testApp.js

실행권한주기./testApp.js

Page 9: Nodejs, PhantomJS, casperJs, YSlow, expressjs

Sample• var fs = require('fs');• var contents = fs.readFile(‘text.txt','utf-8',function(err,contents){• console.log('=========================');• console.log(contents);• console.log('=========================');• console.log('function end');• });• console.log(' 문법 end');

Page 10: Nodejs, PhantomJS, casperJs, YSlow, expressjs

REPL• Python 이나 개발자 도구의 Console 과 같은 대화형

모드• 개발 시 테스트용 등으로 사용하며 save/load 기능

제공

Page 11: Nodejs, PhantomJS, casperJs, YSlow, expressjs

내장 객체 - 1모듈명 설명

Assertion Testing 단정문 모듈

Buffer 바이너리 데이터의 옥텟 스트림 (8 비트 데이터 )  모듈

C/C++ Addons C/C++ 모듈 사용 관련 모듈

Child Processes 자식 프로세스 생성및 관리 모듈

Cluster 멀티코어처리 모듈

Console 콘솔 출력관련 모듈

Crypto 암호화 모듈

Debugger 디버깅 모듈

DNS 도메인 네임 서버 모듈

Domain 도네임 모듈

Events 이벤트 관련 모듈

Page 12: Nodejs, PhantomJS, casperJs, YSlow, expressjs

내장 객체 - 2모듈명 설명

File System(FS) 파일시스템 ( 읽고 / 쓰고 ) 모듈

Globals 글로벌 객체 모듈

HTTP HTTP 서버와 클라이언트 기능 모듈

HTTPS HTTPS 서버와 클라이언트 기능 모듈

Modules 모듈 사용관련 기능

Net 비동기 네트워크 통신 기능 모듈

OS 운영체제 정보를 제공 모듈

Path 파일의 경로 제공 모듈

Process 실행된 프로세서의 대한 정보 제공

Punycode non-ASCII 문자 의 인코딩 함수 제공

Query Strings URL 의 쿼리 문자열을 다루는 함수를 제공

Page 13: Nodejs, PhantomJS, casperJs, YSlow, expressjs

내장 객체 - 3모듈명 설명

Readline 스트림에서 라인 단위로 읽는 기능을 제공REPL 대화식 모드 관련 기능

Stream 스트림을 다루기 위한 추상 인터페이스String Decoder 버퍼를 스트링으로 변환 함수

Timers Javascript 시간처리 관련 함수TLS/SSL OpenSSL 을 이용하는 보안 관련 모듈

TTY 터미널이나 콘솔 관련 기능을 제공UDP/Datagram UDP 의 소켓 (Datagram Socket) 통신 기능을 제공

URL URL 을 다루는 함수를 제공Utilities 출력 및 디버깅용 모듈

VM 자바스크립트를 실행하는 기능을 제공ZLIB 압축 함수를 제공

Page 14: Nodejs, PhantomJS, casperJs, YSlow, expressjs

내장 모듈 StabilityStabil-

ity상태명 설명

0 Deprecated 하위호환성 X, 문제가 될 수 있으며 변경예정

1 Experimen-tal

하위호환성 X, 신생으로 변경되거나 삭제될 수 있음

2 Unstable 하위호환성 △ , 현재 만드는 중

3 Stable 하위호환성 ○ , 마이너 한 변화가 있을 수 있음

4 API Frozen하위호환성 ○ , 테스트 끝난 상태로 앞으로 수정이 없을 예정

5 Locked 하위호환성 ○ , 심각한 버그가 없는 한 수정 안 함

Page 15: Nodejs, PhantomJS, casperJs, YSlow, expressjs

외부 모듈 관리• 전역모드 설치 : /usr/local/lib/node_module

– root $ npm install –g < 패키지명 >

• 지역모드 설치– $ npm install < 패키지명 >

• 특정 버전 설치– $ npm install < 패키지명 >@< 버전 >

• 삭제– $ npm uninstall < 패키지명 >

• 업데이트– $ npm update < 패키지명 >

Page 16: Nodejs, PhantomJS, casperJs, YSlow, expressjs

외부 모듈 관리• 전역모드 설치 : /usr/local/lib/node_module

– root $ npm install –g < 패키지명 >

• 지역모드 설치– $ npm install < 패키지명 >

• 특정 버전 설치– $ npm install < 패키지명 >@< 버전 >

• 삭제– $ npm uninstall < 패키지명 >

• 업데이트– $ npm update < 패키지명 >

Page 17: Nodejs, PhantomJS, casperJs, YSlow, expressjs

웹서비스를 한다면 ?

• 라우팅

• 동적뷰

• 세션

• 쿠키

• 로깅

• 외부 세션 저장소 기능

• 등등

Express

Page 18: Nodejs, PhantomJS, casperJs, YSlow, expressjs

Express 라우팅 예var routes = require('./routes');var user = require('./routes/user');……app.get('/', routes.index); // routes/index.js 실행

app.get('/user/list', user.list); // routes/user.js 의 list functionapp.get('/user/info', user.info); // routes/user.js 의 info function

app.get('/test.json',function(req, res){ //직접 실행 var tempJson = {'id': 'tester', 'message':'HIHI tester'}; res.json(tempJson);});app.get('/hello/:name', function(req, res){ fs.readFile('views/index.jade', 'utf8', function(error,data){ var fn = jade.compile(data); res.writeHead(200,{'Content-Type':'text/html'}); res.end(fn({ name:req.params.name })); });});

Page 19: Nodejs, PhantomJS, casperJs, YSlow, expressjs

화면은 어떻게 그리나 ?• HAML 기반 화면 그리기 (Jade, coffeekup 등 )

– 무슨소린지 잘 모르겠지만 아래의 예를 보면 알 수 있다 .

• 기존 서버사이드에서 화면구성하는 방법 (ejs, swig, handlebars 등 )– ASP, PHP, JSP 등에서 화면 그리는 것과 같은 식으로 개발 할 수 있다 .– 기존 JSP 로 화면 그리는 것이 편한 경우 사용하면 좋을 것 같다 .

• API 를 호출하여 가져온 데이터를 그리는 식의 패턴 (Jsdom 등 )– 서버에서 보여줄 파일을 로딩한 후 jquery 나 angularJs 등을 삽입하여 DOM 에 내용을 변경– Front-End 단에서 JSON 호출 후 템플릿을 이용하여 화면은 그리는 것과 거의 같은 식으로

개발할 수 있다 .

html head title= "I'm Title" link(rel='stylesheet', href='/stylesheets/style.css') body p Welcome to #{name} - for(var i=0;i<2;i++){ p HI #{name} - }

<html> <head> <title>I'm Title</title> <link rel="stylesheet" href="/stylesheets/style.css"/> </head><body><p>Welcome to hong</p><p>HI hong</p><p>HI hong</p></body></html>

Page 20: Nodejs, PhantomJS, casperJs, YSlow, expressjs

PhantomJS• healess webkit 기반 브라우저• 웹사이트 접속 후 렌더링 및 스크립트등의 처리가

완료된 DOCUMENT 획득• HTML 의 DOM API 지원 ( 예 : getElement-

ById)• 웹사이트 캡처• PhantomJS 는 단독 실행이 가능하며 node 에서

사용하기 위해서는 node-phantom( 브릿지 드라이버 ) 를 설치하여야 함

Page 21: Nodejs, PhantomJS, casperJs, YSlow, expressjs

CasperJS• PhantomJS 를 기반하여 phantomJS 을 가지고 있음• 사용자 액션 기능 제공– Form 입력– Submit(Click)

• Javascript 삽입 ( 예 : Jquery, Jindo 등 ) 후 처리 가능

• 전체 화면 캡처 및 특정 Element 캡처• casperjs 는 단독 실행이 가능하며 node 에 붙여서

사용하기 위해서는 SpookyJS( 브릿지 드라이버 ) 가 필요하다 .

Page 22: Nodejs, PhantomJS, casperJs, YSlow, expressjs

CasperJS 데이터 추출• var casper = require("casper").create({• viewportSize: {• width: 1024,• height: 768• }• });• casper.start('http://pann.nate.com/', function() {• this.captureSelector('pann_talk.png', 'div .today-talk',function(){• console.log('이미지 저장 : nate_pann.png');• });

• var result = this.evaluate(function(){• var title = document.title;• var element = document.querySelector('div .today-talk').outerText;• return {'title':title, 'element': element}• });

• console.log('Casper loading Page title : ' + result.title);• console.log('Casper loading capture element outerText : \n' + result.element);• });• casper.run();

Page 23: Nodejs, PhantomJS, casperJs, YSlow, expressjs

CasperJS 데이터 추출

Page 24: Nodejs, PhantomJS, casperJs, YSlow, expressjs

CasperJS 으로 로그인

Page 25: Nodejs, PhantomJS, casperJs, YSlow, expressjs

CasperJS 으로 로그인var casper = require("casper").create();casper.start('https://login.danawa.com/login.php?url=http://bbs.danawa.com/point/in-

dex.php');

casper.then(function() { this.fill('form#frmLogin',{ 'txtId' : ‘ 아이디 ', 'pwdPasswd' : ‘ 패스워드 ' }, true); this.capture('danawa_nologin.png',{ top: 0, left: 0, width: 1024, height: 700 });});casper.thenOpen('http://bbs.danawa.com/point/index.php', function(){ this.capture('danawa_login.png',{ top: 0, left: 0, width: 1024, height: 700 });});casper.run();

Page 26: Nodejs, PhantomJS, casperJs, YSlow, expressjs

CasperJS 으로 로그인

Page 27: Nodejs, PhantomJS, casperJs, YSlow, expressjs

YSlowJS• PhantomJS 기반• 웹사이트에 대한 성능 분석 도구 • 성능 분석된 데이터 추출하여 원하는 포맷으로

리턴- Json, Xml, Plain text, Tap, JUnit

• 임의로 정한 등급에 따라 성공 여부 판단

Page 28: Nodejs, PhantomJS, casperJs, YSlow, expressjs

YSlowJS - 결과

Page 29: Nodejs, PhantomJS, casperJs, YSlow, expressjs

Async• 중첩 callback 이 많아 짐에 따라 이를

일목요연하게 정리하기 위한 모듈• 각 function 을 흐름제어 한다 .• 지금은 잘 모르겠지만 개발을 하게 되면

중첩 Callback 이 많아짐에 따라 필요성을 느끼게 될 것 이다 . 그때 찾아보면 좋을 것 같다 .

• 참고 URL : http://nodeqa.com/nodejs_ref/3

Page 30: Nodejs, PhantomJS, casperJs, YSlow, expressjs

활용 ?• Prototyping

• 간단한 웹서비스

• 간단한 로직의 대용량 처리

• 빠른 응답 시간을 요구하는 어플리케이션

• File Up/Download 같은 I/O 서비스

• Test Framework 및 웹사이트 성능 분석

• 채팅 서비스 (socket.io)

• 서버 배치 프로그래밍

• REST API 개발

• 모니터링 시스템

• Android, iOS 푸시서비스

Page 31: Nodejs, PhantomJS, casperJs, YSlow, expressjs

소스를 조금 볼까요 ?

Page 32: Nodejs, PhantomJS, casperJs, YSlow, expressjs

참고 사이트• Nodejs 공식 사이트

– http://nodejs.org/

• Nodejs opensource 모듈 정보– https://www.npmjs.org/

• Nodejs opensource 모듈 사용 빈도 / 태깅 정리 사이트– https://nodejsmodules.org/

• Express 가이드 ( 한글 ), Socket.io 기능을 이용한 시스템 모니터링– http://firejune.io/– http://firejune.io/express/guide

• Nodejs 내장 모듈 한글 Doc– http://nodejs-kr.org/

Page 33: Nodejs, PhantomJS, casperJs, YSlow, expressjs

참고 사이트• Nodejs 관련 블로그– http://nodeqa.com/

• Phantomjs 공식홈페이지– http://phantomjs.org/

• Casperjs Doc– http://casperjs.readthedocs.org/en/

• Phantomjs, Casperjs, App 푸시 서비스등 참조 블로그– http://blog.saltfactory.net/category/Javascript

Page 34: Nodejs, PhantomJS, casperJs, YSlow, expressjs

THE END