레이블이 node.js인 게시물을 표시합니다. 모든 게시물 표시
레이블이 node.js인 게시물을 표시합니다. 모든 게시물 표시

2016년 6월 14일 화요일

The Node Beginner Book 대충 정리

The Node Beginner Book 대충 정리

보면서 눈에 띄는 것 만 대충 정리함.

http://www.nodebeginner.org/index-kr.html


Node.js

- server side JavaScript
 : Server side JavaScript 실행환경과 라이브러리로 이루어져 있음.

- Event driven callbacks
 : event에 대한 callback을 등록하여 처리 하도록 함.
   각 event 상황에 대해서 처리하도록 callback을 등록하여 단순해 지지만
   callback 내에서 과도한 operation을 처리할 경우 성능 문제 발생 가능

http://debuggable.com/posts/understanding-node-js:4bd98440-45e4-4a9a-8ef7-0f7ecbdd56cb


[Documentation에서 설명하는 기본 use scenario]

- 웹페이지 제공 => HTTP 서버가 필요.
- 서버는 어떤 URL 요청(request)에 응답 => 요청과 요청을 처리할 핸들러들을 위한 라우터(router) 필요.
- 서버로 도착한 요청 처리 => 요청 핸들러(request handlers)가 필요.
- 라우터에서의 POST 데이터 처리, request handler 들에게 넘기기 위한 request 가공 => 요청 데이터 핸들링(request data handling)이 필요.
- URL 요청 시 내용 표시 => request handler 들이 사용자 브라우저로 콘텐트를 보내기 위해 사용할 수 있는 뷰 로직(view logic)이 필요.
- 이미지들을 업로드 => 업로드 핸들링(upload handling)이 필요.


[Hello world example]

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;
http server를 사용해서 hello world를 만들 것이므로
require로 http 모듈을 사용할 수 있도록 함.

http server 모듈의 request event를수신했을 때 response로
text/plain content type으로 "hello world"를 전송함.
http://nodejs.org/api/http.html#http_class_http_server

exports는 함수를 외부에서 사용할 수 있도록 할 때 사용.



index.js


var server = require("./server");

server.start();
다른 js파일을 내장 모듈 불러오듯 require를 사용해서 불러오고 export된 함수를 사용.


[request 정보 확인 for route]


                               url.parse(string).query
                                           |
           url.parse(string).pathname      |
                       |                   |
                       |                   |
                     ------ -------------------
http://localhost:8888/start?foo=bar&hello=world
                                ---       -----
                                 |          |
                                 |          |
              querystring(string)["foo"]    |
                                            |
                         querystring(string)["hello"]
request의 method, path, query 들을 확인하여 적절한 handler에서 처리하기 위해 필요한 함수들 



request handler들을 path에 따라 등록하고 route하는 예제


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.");
}

exports.start = start;
기본 hello world server에서 변경된 점은
url의 pathname을 확인하여 route하는 루틴이 포함된 점이다.
간단한 예제라 route의 결과를 가지고 response를 보내는 것이 구현되어 있지는 않음.



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;
hanlder들 중에서 pathname의 key를 가진 function object를 찾아서 실행함.



var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;

server.start(router.route, handle);
url path에 따른 handler들을 매핑한 뒤
server로 router와 handle을 넘겨서 시작함.


[TODOs]

- understanding node.js : http://debuggable.com/posts/understanding-node-js:4bd98440-45e4-4a9a-8ef7-0f7ecbdd56cb

- dependency injection pattern : http://martinfowler.com/articles/injection.html

- function programming 관련 : http://steve-yegge.blogspot.kr/2006/03/execution-in-kingdom-of-nouns.html





2015년 2월 10일 화요일

Node.js 대충 정리

[참고]
http://nodejs.org/

http://en.wikipedia.org/wiki/Node.js
http://ko.wikipedia.org/wiki/Node.js
http://www.slideshare.net/kazikai/nodejs-29836481 (내용 괜찮음)
http://bcho.tistory.com/885
http://www.nodebeginner.org/index-kr.html
http://helloworld.naver.com/helloworld/textyle/12864
http://nodeqa.com/nodejs_ref/65


[History]
- Node.js는 Ryan Dahl(Joyent사)에 의해 처음 시작. (2009년)
 : Flickr의 file upload 진행창을 보았을 때, 업로드 상태를 알지 못해 서버로 Query를 해야 한다는 점을 고민하다 Node.js를 고안하였다고 함.

- 최초 Node.js 버전은 Linux 기반으로 출시. (2009년)
 : Inangural JSConf EU conference에서 발표 후 국제적인 관심을 끌기 시작함.

- Node.js의 패키지매니저인 npm은 2011년에 처음 소개되었다.

- Microsoft는 Joyent사와 파트너쉽을 맺음 (2011년 6월)
 : Node.js의 Windows버전을 7월에 출시 (2011년 7월)

[특징]
- 구글 크롬 웹브라우저의 자바스크립트 엔진인 V8 기반 TCP library와 HTTP 서버 제공
- Single Thread 기반 Event driven 방식
- Non-Blocking I/O
- CommonJS 모듈 시스템 => http://helloworld.naver.com/helloworld/textyle/12864
- C, C++로 만들어짐.


[기본 module]

. Node.js 는 stable api / unstable api 가 나눠짐
. 각 api 의 level이 있음 : http://nodejs.org/api/documentation.html
. 개발시에 필히 몇레벨인지 확인한후, 사용하는것이 필요


[클러스터]
. 노드는 싱글 스레드로 동작하기 때문에 멀티프로세스의 이점을 얻지 못함.
. I/O에 대한 처리는 이벤트 루프를 통해 좋은 성능을 보여주지만 CPU 계산량이 많은 부분에는 취약한 면이 있음.
. 이를 클러스터 모듈을 통해 해소할 수 있음.


[유용한 확장 모듈들]

[node-supervisor, 스크립트 수정 시 재실행 해주는 확장 모듈]
. 변경된 스크립트를 재실행 하지 않아도 종료 후 다시 실행해 줌.
. 또한 application이 종료되면 무한으로 다시 실행 함.

. 설치
 : npm install –g supervisor
. 사용 방법
 : supervisor xxxx.js

[node-schedule, 스케줄링 확장 모듈]

. Crontab과 같이 스케줄링 관리를 하는 모듈 
. 세가지 스케줄링 방법 제공
 1. new Data로 지정한 날짜와 시간에 작동
 2. RecurrenceRule 함수로 동작할 시간의 규칙 지정
 3. 크론 스타일의 반복 주기 설정

[forever, 노드 애플리케이션 관리 확장 모듈]

. 데몬을 사용해서 node 애플리케이션을 실행하는 것과 같이 실행, 관리를 도움
. cmdline에서 사용하는 명령형 도구 이므로 글로벌로 설치
. 실행중인 프로세스 리스트, 정보 확인 가능, stop/restart 관리 가능
. 어플리 종료되면 자동으로 재실행

. 설치
 1. cmdline에서 사용
  $ [sudo] npm install forever -g
 2. 프로그래밍에서 사용
  $ cd /path/to/your/project
  $ [sudo] npm install forever-monitor

. 주요 명령어
 1. 실행
  $ forever start xxxx.js
 2. 실행 리스트 확인
  $ forever list
 3. 실행 중지 (리스트의 [X] 번호)
  $ forever stop 번호
 4. 재시작
  $ forever restart 번호


[npm]
https://www.npmjs.com/
http://en.wikipedia.org/wiki/Npm_(software)
http://forum.falinux.com/zbxe/index.php?document_srl=572898&mid=lecture_tip

. 아이작 슐레터(Isaac Z. Schlueter)가 만든 노드를 위한 패키지 매니저
. 노드에서 사용되는 모듈들의 설치 및 의존성을 관리해 주는 도구
. Java의 maven 처럼 package.json 파일에 modul간 dependenc에 따라서 의존성이 있는 모듈들을 같이 설치 함.
. 주요 명령어
 - npm list xxxx [-g]
 - npm install xxxx [-g]
 - npm remove xxxx [-g]

- windows에서 설치 후 npm 실행 안될 때
c:\users\아이디\AppData\Roaming\npm 폴더 생성
(win 7 기준이고 에러 발생 시 경로가 나옴)

- proxy 설정
npm config set proxy http://xxxxx:yyyy
npm config set https-proxy http://xxxx:yyyy

- UNABLE_TO_VERIFY_LEAF_SIGNATURE 가 발생할 경우
npm config set strict-ssl false
(왠만하면 인증서 등록해서 true로 다시 변경하는게 좋음)


[socket.io]

http://socket.io/