2015년 4월 22일 수요일

Mac, Node.js 학습 6일차] 외부 모듈

Node.js에서 제공하는 내부 모듈이 아닌 외부 개발자가 만들어 배포하는 모듈을 외부 모듈이라 한다.
  - 외부 모듈 설치 방법
    $npm install 모듈명

1. ejs 모듈
템플리 엔진 모듈로써 특정 형식의 문자열을 HTML 형식의 문자열로 변환함
  - 모듈 설치
baesunghan:~/Documents/workspace/nodejs$npm instal ejs
ejs@2.3.1 node_modules/ejs
baesunghan:~/Documents/workspace/nodejs$

  - ejs 모듈 Method
    . render : ejs 문자열을 HTML 문자열로 변환한다.
  - ejs 에서 사용되는 특수 태그
    . <% Javascript code %> : javascript code를 기술, ex) <% var name = 'Toven' %>
    . <%= value %> : 변수값을 출력, ex) <%= name %>
  - 특수 태그로 데이터 전달 : 아래와 같이 render에 데이터 값 입력
response.end(ejs.render(ejsdata, {
name: 'Toven',
desc: 'Ejs Module Sample'
}));
  - 사용 예
baesunghan:~/Documents/workspace/nodejs$cat ejs.js
// 모듈을 추출합니다.
var http = require('http');
var ejs = require('ejs');

// 웹 서버를 생성 및 실행합니다.
http.createServer(function (request, response) {
var ejsdata = ejsMsg();
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(ejs.render(ejsdata, {
name: 'Toven',
desc: 'Ejs Module Sample'
}));

}).listen(18080, function() {
console.log('Server running at http://127.0.0.1:18080/');
});

var ejsMsg = function() {
var str = '';
str = str + '<h1><%= name %></h1>';
str = str + '<p><%= desc %></p>';
str = str + '<hr/>';
str = str + '<% for(var i=0; i<10; i++) { %>';
str = str + ' <h2>Count <%= i %> </h2>';
str = str + '<% } %>';

return str;
}baesunghan:~/Documents/workspace/nodejs$

2. jade 모듈
템플릿 엔진 모듈
  - 모듈 설치
baesunghan:~/Documents/workspace/nodejs$npm install jade
jade@1.9.2 node_modules/jade
├── character-parser@1.2.1
├── void-elements@2.0.1
├── commander@2.6.0
├── mkdirp@0.5.0 (minimist@0.0.8)
├── with@4.0.3 (acorn-globals@1.0.4, acorn@1.0.3)
├── constantinople@3.0.1 (acorn-globals@1.0.4)
└── transformers@2.1.0 (promise@2.0.0, css@1.0.8, uglify-js@2.2.5)
baesunghan:~/Documents/workspace/nodejs$

  - jade 모듈의 Method
    . compile() : jade 문자열을 HTML 문자열로 바꿀수 있는 함수 생성

  - .jade 파일 작성 예
baesunghan:~/Documents/workspace/nodejs$cat jadedata.jade
doctype html
html
head
title Index Page
body
// JADE comment
h1 Hello Jade!!!
h2
hr
a(href='http://wechatmanager.co.kr') Link Wechatmanager

baesunghan:~/Documents/workspace/nodejs$
 
  - .jade 파일을 읽어서 client로 출력하는 예제
baesunghan:~/Documents/workspace/nodejs$cat jade.js
// 모듈을 추출합니다.
var http = require('http');
var jade = require('jade');
var fs = require('fs');

// 웹 서버를 생성 및 실행합니다.
http.createServer(function (request, response) {
// jade 파일을 읽음
fs.readFile('jadedata.jade', 'UTF-8', function(error, data) {
console.log(data);
var fn = jade.compile(data);
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(fn());

});

}).listen(18080, function() {
console.log('Server running at http://127.0.0.1:18080/');
});
baesunghan:~/Documents/workspace/nodejs$

    => 실행 결과 생성 html tag

  - .jade 파일에 사용된 특수 기호
    . - javascript : javascript 를 기술할 수 있음
    . #{Value} : 데이터 출력
    . = Value : 데이터 출력
  - 특수 Tag 사용 .jade  파일 예
baesunghan:~/Documents/workspace/nodejs$cat jadedata1.jade
doctype html
html
head
title Index Page
body
// JADE comment
h1 Hello #{name}
h2= desc
hr
// 자바스크립터 기술
- for(var i=0; i<10; i++) {
p
a(href='http://wechatmanager.co.kr') Link Wechatmanager
- }

baesunghan:~/Documents/workspace/nodejs$
  - 특수 기호에 데이터를 대치해서 출력하는 예
baesunghan:~/Documents/workspace/nodejs$cat jade.js
// 모듈을 추출합니다.
var http = require('http');
var jade = require('jade');
var fs = require('fs');

// 웹 서버를 생성 및 실행합니다.
http.createServer(function (request, response) {
// jade 파일을 읽음
fs.readFile('jadedata1.jade', 'UTF-8', function(error, data) {
console.log(data);
var fn = jade.compile(data);
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(fn({
name:'Teoven',
desc:'Jade Testing'
}));

});

}).listen(18080, function() {
console.log('Server running at http://127.0.0.1:18080/');
});
baesunghan:~/Documents/workspace/nodejs$

    => 실행 결과
    ==> "/자바스크립터 기술" 한글이 깨짐
    ==> readFile에서 encoding을 "EUC-KR"로 변경하면 다음 오류 발생함, 확인해보니 encoding은 "ascii", "utf8", "base64"만 가능함.
baesunghan:~/Documents/workspace/nodejs$node jade.js
Server running at http://127.0.0.1:18080/
fs.js:101
    throw new Error('Unknown encoding: ' + encoding);
          ^
Error: Unknown encoding: EUC-KR
    at assertEncoding (fs.js:101:11)
    at Object.fs.readFile (fs.js:252:3)
    at Server.<anonymous> (/Users/baesunghan/Documents/workspace/nodejs/jade.js:9:5)
    at Server.emit (events.js:110:17)
    at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:491:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:111:23)
    at Socket.socketOnData (_http_server.js:343:22)
    at Socket.emit (events.js:107:17)
    at readableAddChunk (_stream_readable.js:163:16)
    at Socket.Readable.push (_stream_readable.js:126:10)
   ===> 해결방법, response.writeHead에 다음과 같이 설정
     response.writeHead(200, {'Content-Type': 'text/html;charset=UTF-8'});
     <출력결과>



2015년 4월 21일 화요일

MacBook에서 UltraNav 키보드 사용하기›

* 모델
  -  MacBook Pro 13'', OS Yosemite v10.10.3
    . 키배열 : fn, Control, option(alt), command, Space


  - UltraNav(Model : SK-8855)
    . Fn, Control, Window, Alt, Space


* 최초 키보드 연결시 문제점
  - Command  키 : Window 키로 동작하여 불편함
  - 빨콩 이동속도 느림.
  - 좌/우클릭키 중간 스크롤키+빨콩 동작안함


  • * 키 조합 재 매핑

  - 참고 : [Mac] 맥과 울트라나브를 붙이기 - 환경설정에서 맥의 키와 비슷한 조합 만들기. :: 까만거북이의 달리는 이야기
  - 울트라나브의 Window Key <-> MacbookPro Option
  - 울트라나브의 Alt <-> MacbookPro Command
1. 시스템 환경설정 > 키보드 실행

2. 키보드에서 "보조 키..." 버튼 클릭

3. 보조키 화면에서 다음내역 변경 후 승인 
  - 키보드 : ThinkPad USB Keyboard with TrackPoint
  - Option 키 : Command
  - Command 키 : Option




  • * 빨콩 이동속도 느림

환경설정 > 마우스 에서 이동속도 조정

다른 방법으로 터미널에서 아래 명령 수행 후 재부팅 하면 된다고함(해보지는 않음). 뒤에 숫자가 커질수록 빨라짐, 현재 설정값은 "3"으로 확인함.
$defaults read -g com.apple.mouse.scaling 6


  • 좌/우클릭키 중간 스크롤키+빨콩 동작하기

  - 참고 : 오리대마왕님 집
controllermate를 이용하여 문제를 해결할 수 있다고 함.
1. ControllerMate 다운로드
빨콩 스크롤 기능은 무상 다운로드만 해도 된다고 함.
 다운로드 사이트 : http://www.orderedbytes.com/controllermate/

2. ControllerMate 설치



3. ControllerMate 실행

4. 좌측 Programming Items에서 Welcomes, Get started를 우클릭해서 delete한다.
5. Programming Items에 create Program Page/Group으로 아래와 같이 생성한다. 명칭 변경은 Inspector내 Properties 에서 변경한다.
    같은 방법으로 Scroll Function 아래에 create Program Page와 create Virtual Device > Virtual Mouse을 생성한다.

6. 좌측 Programming Items에서 Control 선택 후 Platte에서 Controllers 마우스 아이콘의 "ThinkPad USB Keyboard.."를 선택한 후 Device에서 "Button #3 Building Block ..."을 Edit Pane으로 Drop & Drop
 좌측의 Scroll Function을 Edit Pane으로 Drag * Drop

7. 좌측 Programming Items에서 Scolling을 선택 후 6과 같은 방식으로 추가한다.
  먼저 Controllers에서 마우스 아이콘의 "ThinkPad USB Keyboard.."를 선택한 후 Device에서 "ThinkPad USB Keyboard.. Y-Axis"를 Drag & Drop
  두번째로 Edit Pane에서 우클릭 create Building Block > Calculation > Axis Calibration 선택
  세번째로 Controller에서 Virtual Mouse를 선택하고 Device에서 "New Virtual Mouse Wheel"을 선택한다.
  Axis Calibration에서 Limit값을  -20 ~ 20, -1~1으로 조정

  center 값을 각각 0, 2로 조정

8. 좌측 Programmming Items에서 New Virtual Mouse 를 선택 후 Number of Buttons의 값을 2로 조정

==> 문제는 ControllerMate를 실행중에는 Wheel 기능이 사파리에서 동작하지만 닫아버리면 동작하지 않는다. 뭐가 잘못된 것인가? ( it works well. But if stop the ControllerMate(app close), it doesn't work in Safari. What 's wrong?)
==> 다시 해보니 잘 동작한다. 좀더 테스트를 해봐야 할 것 같다. (Now, it works well in Safari. I will test the function more.)






2015년 4월 20일 월요일

Mac, Node.js 학습 5일차] 웹 개발

웹 브라우즈를 통한 웹 서비스 작성을 학습한다.

1. http 모듈
웹 개발을 위한 모듈로써 웹 서버를 위한 server 객체, response 객체등을 생성하기 위한 모듈이다.
웹개발을 위한 기본 개념인 http request(요청)/response(응답)에 대한 상세내역은 다음 사이트에서 참조한다.(Jonic:HTTP 프로토콜 분석)

  - 특정 웹 페이지에 대한 http 요청/응답에 대한 상세 정보 보기
    . 사파리 : 페이지에서 우클릭 > 요소점검으로 표시된 창의 우측 "리소스"에서 확인
    . 크롬 : 페잊에서 우클릭 > 요소점검으로 표시된 창의 "Network" 탭에서 확인

2. Server 객체
server 객체를 생성해서 웹 서버를 실행한다. 웹 브라우즈에서 http request에 대해서 business logic을 처리후 웹 브라우즈로 http response 를 보내준다.
  - 객체 Method
    . listen(port, [callback]); : 서버 실행
    . close() : 서버 종료
  - 객체 Event
    . connection : 클라이언트가 접속할때 발생하는 이벤트
    . request : 클라이언트가 요청할때 발생하는 이벤트
    . close : 클라이어트가 접속을 끊을 발생하는 이벤트
    . checkContinue : 클라이언트가 지속적으로 연결하고 있을때 발생하는 이벤트로써 client에서 Expect: 100-continue와 함께 request 할때 발생함
    . upgrade : 클라이언트가 upgrade(?)를 요청할때 발생하는 이벤트
    . clientError : 클라이언트에서 오류가 발생할 때 발생하는 이벤트

  - 사용 예
baesunghan:~/Documents/workspace/nodejs$cat node.server1.js
// 모듈을 추출합니다.
var http = require('http');

// 웹 서버 객체 생성
var server = http.createServer();


// 서버 객체에 event 연결
server.on('request', function() {
console.log('Request On');
});
server.on('connetion', function() {
console.log('Connection on');
});
server.on('close', function() {
console.log('Close on');
});

// 서버 실행
server.listen(18080, function() {
console.log('Server running at http://127.0.0.1:18080/');
});
baesunghan:~/Documents/workspace/nodejs$

    => 웹 브라우즈에 아무런 응답이 없음, 이는 response 이벤트가 정의되지 않아서 일어나는 것임, 서버 console에는 로그가 표시됨.
    => 이상한 것은 "Connection on" 메시지가 서버 console 창에 출력되지 않음. 추후 확이 필요함.
    => 서버 종료는 Ctrl + C로 종료해야 아래 오류 발생하지 않음.

  - listen EADDRINUSE 오류 처리
    . 최초 실행은 정상 실행되었음, 서버를 Ctrl + Z로 종료함
baesunghan:~/Documents/workspace/nodejs$node node.server1.js
Server running at http://127.0.0.1:18080/
Request On
Request On
^Z
[1]+  Stopped                 node node.server1.js
baesunghan:~/Documents/workspace/nodejs$
    . 이후 다시 해당 서버를 실행했지만 다음 오류가 발생함.
baesunghan:~/Documents/workspace/nodejs$node node.server1.js
events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: listen EADDRINUSE
    at exports._errnoException (util.js:746:11)
    at Server._listen2 (net.js:1146:14)
    at listen (net.js:1172:10)
    at Server.listen (net.js:1257:5)
    at Object.<anonymous> (/Users/baesunghan/Documents/workspace/nodejs/node.server1.js:20:8)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
baesunghan:~/Documents/workspace/nodejs$

    => 발생 이유는 서버가 정상 종료되지 않아 18080에 대한 서버가 실행중임, 아래 내용 프로세스 확인 후 kill 한 후 다시 실행한다.
baesunghan:~/Documents/workspace/nodejs$ps -ef | grep node
  501   760   449   0 12:56PM ttys000    0:00.12 node node.server1.js
  501   807   797   0  1:08PM ttys001    0:00.00 grep node
baesunghan:~/Documents/workspace/nodejs$kill -9 760
baesunghan:~/Documents/workspace/nodejs$ps -ef | grep node
  501   811   797   0  1:11PM ttys001    0:00.00 grep node
baesunghan:~/Documents/workspace/nodejs$

3. response 객체
웹 서버에서 클라이언트로 응답하기 위한 객체
  - 제공 메소드
    . wirteHead(statusCode, object);  : 응답 헤더를 작성
    . end([data], [encoding]) : 응답 본문을 작성
  - 사용 예
baesunghan:~/Documents/workspace/nodejs$cat node.server1.js
// 모듈을 추출합니다.
var http = require('http');

// 웹 서버 객체 생성
var server = http.createServer(function(request, response) {
response.writeHead(200, { 'Content-Type': 'text/html'});
response.end('<h1>Hello World!!!')
});

  - 일반적으로 html 파일을 읽어서 클라이언트로 제공하는 방식 사용함
  - html 파일 사용 예
baesunghan:~/Documents/workspace/nodejs$cat node.server1.js
// 모듈을 추출합니다.
var http = require('http');
var fs = require('fs');

// 웹 서버 객체 생성
var server = http.createServer(function(request, response) {
// read html file
fs.readFile('htmlsample.html', function(error, data) {
response.writeHead(200, { 'Content-Type': 'text/html'});
response.end(data);

});
});

  -  이미지나 미디어 파일 사용 예
baesunghan:~/Documents/workspace/nodejs$cat node.server2.js
// 모듈을 추출합니다.
var http = require('http');
var fs = require('fs');

// 웹 서버 객체 생성
var server = http.createServer(function(request, response) {
// read html file
fs.readFile('flower.jpg', function(error, data) {
response.writeHead(200, { 'Content-Type': 'image/jpeg'});
response.end(data);

});
});

  - response객체의 응답 메시지를 위한  Context-Type : MIME 형식, 상세 참조(MIME Types List - FreeFormatter.com)
    . text/plain : 기본적인 텍스트
    . text/html : HTML 문서
    . text/css : CSS 문서
    . text/xml : XML 문서
    . image/jpeg : JPG/JPEG 이미지 파일
    . image/png : PNG 이미지 파일
    . video/mpeg : MPEG 비디오 파일
    . audio/mp3 : MP3 음악 파일


4. 쿠키 생성
일정 기간동안 서버나 클라이언트에 접속에 관련된 정보를 저장하는 역할을 합니다. 로그인시 이전 접속 id를 기억하는 기능 등을 사용할때 쿠키를 사용함.
  - 사용 : response 객체에 Set-Cookie로 key=value; 형태로 저장합니다
  - 사용 예
// 모듈을 추출합니다.
var http = require('http');
var fs = require('fs');

// 웹 서버 객체 생성
var server = http.createServer(function(request, response) {
// read html file
fs.readFile('flower.jpg', function(error, data) {
response.writeHead(200, { 
'Content-Type': 'image/jpeg',
'Set-Cookie': ['id=bsh', 'name=Toven']});
response.end(data);

});
});

5. 페이지 이동(redirection)
특정 페이지를 호출시 다른 페이지로 이동할 경우 사용함.
  - 사용 : response 객체에 StatusCode : 302, Location 항목값 설정
  - 사용 예
baesunghan:~/Documents/workspace/nodejs$cat node.server2.js
// 모듈을 추출합니다.
var http = require('http');
var fs = require('fs');

// 웹 서버 객체 생성
var server = http.createServer(function(request, response) {
// read html file
fs.readFile('flower.jpg', function(error, data) {
response.writeHead(302, { 
'Content-Type': 'text/html',
'Set-Cookie': ['id=bsh', 'name=Toven'],
'Location': 'http://wechatmanager.co.kr'});
response.end(request.headers.cookie);

});
});

6. request 객체
클라이언트에서 호출시 request 이벤트가 발생하고 request 객체가 생성됨
  - 객체 속성
    . method : 클라이언트의 요청 방식, GET/POST/PUT
    . url : 클라이언트가 요청한 url
    . headers : 요청 메시지의 header 정보
    . trailers : 메시지 트레일러 정보
    . httpVersion : HTTP Protocol 버젼 정보

6.1 url 속성을 사용한 페이지 구분 처리
클라이언트에서 호출하는 url 정보에 따라서 각기 다른 페이지가 표시되도록 처리하는 방식
  - 사용 예
baesunghan:~/Documents/workspace/nodejs$cat app01.js
// 모듈을 추출합니다.
var http = require('http');
var fs = require('fs');
var url = require('url');

// 웹 서버 객체 생성
var server = http.createServer(function(request, response) {

var pathname = url.parse(request.url).pathname;
var filename = "";
console.log(pathname);

if (pathname == "/") {
filename = 'index.html';
} else if (pathname == '/other') { 
filename = 'other.html';
}
// read html file
fs.readFile(filename, function(error, data) {
response.writeHead(200, { 'Content-Type': 'text/html'});
response.end(data);

});
});

// 서버 실행
server.listen(18080, function() {
console.log('Server running at http://127.0.0.1:18080/');
});
baesunghan:~/Documents/workspace/nodejs$

 이외에도 method 속성(GET, POST 등)을 이용한 방법, GET 호출 매개변수, POST 호출 매개변수 방법등으로 페이지 구분 처리가 가능함.
   - 사용 예
baesunghan:~/Documents/workspace/nodejs$cat app02.js
// 모듈을 추출합니다.
var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');

// 웹 서버 객체 생성
var server = http.createServer(function(request, response) {
console.log(request.method);
var pathname = '';
var filename = "";
if (request.method == 'GET') {
// Get 으로 넘어온 파라메타에서 page에 값을 추룰해서 파일로 읽는다.
var query = url.parse(request.url).query;
var param = qs.parse(query);
console.log('query : %s', query);
console.log('querystring : %s', param);
console.log('query : page value : %s', query.page);
console.log('query string : page value : %s', param.page);
filename = param.page + '.html';
console.log(filename);
// read html file
fs.readFile(filename, function(error, data) {
response.writeHead(200, { 'Content-Type': 'text/html'});
response.end(data);

});

} else if (request.method == 'POST') {
request.on('data', function(data) {
var param = qs.parse(data);
response.writeHead(200, { 'Content-Type': 'text/html'});
response.end(param);
})

}
});

// 서버 실행
server.listen(18080, function() {
console.log('Server running at http://127.0.0.1:18080/');
});
baesunghan:~/Documents/workspace/nodejs$

    => parammeter로 넘어온 query 값 parsing을 위해서 querystring을 이용하여 JSON 으로 객체화한다. 반대 처리는 query.stringify를 이용하면 된다. [참조 : 3일차 학습 중 4. Query String 모듈]

Mac, Node.js 학습 4일차] 이벤트

 Node.js는 이벤트기반으로 동작하는 비동기식 프로그래밍입니다. 다른말로 Single Thread 기반의 Non-block 비동기식 프로그래밍입니다.
이벤트 기반 프로그래밍을 위한 이벤트 연결 방법에 대해서 학습합니다.

1. 이벤트 연결
  - 연결 Method
    . on(eventName, eventHandler);
  - 연결 예
baesunghan:~/Documents/workspace/nodejs$cat event.connect.js
// Process 객체에 exit 이벤트를 연결합니다.
process.on('exit', function() {
console.log('Bye Bye');
});

// process 객체에 uncaughtException 이벤트 연결
process.on('uncaughtException', function (error) {
console.log('Occurred uncaughtException!!!!');
});

  - 한 이벤트에 10개가 넘는 이벤트 리스너를 연결하면 경고가 발생함
  - 이벤트 리스너 연결 개수 조정 Method
    . setMaxListeners(limit)
  - 이벤트 제거
    . removeListener(eventName, handler)
    . removeAllListener([eventName])
  - 이벤트 리스너를 한번만 실행할 경우
    . once(eventName, eventHandler)
  - 이벤트 강제 발생, 단 process의 exit 이벤트를 강제 호출해도 프로그램은 종료되지 않고 이벤트 리스너만 실행됨
    . emit(event, [arg1], [arg2], ...)

2015년 4월 19일 일요일

Mac, Node.js 학습 3일차] 기본 내장 모듈

1. Node.js에 대한 기본 API 정보
  - http://nodejs.org/api/

 2. os 모듈
  - 운영체제 관련 정보에 관한 기본적인 기능을 제공하는 모듈
  - 제공 메소드
     . hostname() : Host Name
     . type() : OS 이름
     . platform() : OS Platform
     . uptime() : OS가 실행된 시간
     . totlamem() : 시스템 총 사용 메모리
     . freemem() : 시스템의 가용 메모리
     . cpus() : CPU 정보
     . 그외 tempdir(), endianness() 등의 정보 제공
  - 사용 예
baesunghan:~/Documents/workspace/nodejs$cat module.os.js
// OS 모듈을 활성화
var os = require('os');

// 모듈 사용
console.log(os.hostname());
console.log(os.type());
console.log(os.uptime());
console.log(os.totalmem());
console.log(os.freemem());

baesunghan:~/Documents/workspace/nodejs$node module.os.js
Tovensui-MacBook-Pro.local
Darwin
4233
8589934592
518901760
baesunghan:~/Documents/workspace/nodejs$


3. url 모듈
  - url을 호출하고 Parsing 하는 모듈
  - 제공 메소드
    . parse : Url 문자열을 URL 객체로 변환해 리턴
    . format : URL 객체를 URL 문자열로 변환해 리턴
    . resolve : 매개변수를 조합하여 완전한 Url 문자열을 생성해 리턴
  - 사용 예
baesunghan:~/Documents/workspace/nodejs$cat module.url.js
// 모듈 객체 생성
var url = require('url');

// 모듈 사용
var parsedObj = url.parse('http://www.wingkostory.com//news/view.do?news_category_no=1&news_no=6685');
console.log(parsedObj);

baesunghan:~/Documents/workspace/nodejs$node module.url.js
{ protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'www.wingkostory.com',
  port: null,
  hostname: 'www.wingkostory.com',
  hash: null,
  search: '?news_category_no=1&news_no=6685',
  query: 'news_category_no=1&news_no=6685',
  pathname: '//news/view.do',
  path: '//news/view.do?news_category_no=1&news_no=6685',
  href: 'http://www.wingkostory.com//news/view.do?news_category_no=1&news_no=6685' }
baesunghan:~/Documents/workspace/nodejs$


4. Query String 모듈
  - url 에서 사용되는 query를 객체로 변환하거나 객체를 스트링으로 변환하는 모듈
  - url 객체의 query 부분을 만들어 준다.
  - 제공 Method
    . stringigy() : 쿼리 객체(JSON : {'id':'bsh', 'name':'Toven'})를 쿼리 문자열(id=bsh&name=Toven)로 변환
    . parse() : 쿼리 문자열을 쿼리 객체(JSON)로 변환
  - 사용 예
    var qs = require('query string');
    var param = qs.parse('id=bsh&name=Toven');
    console.log(param.id);
    console.log(param.name);
    var str = qs.stringify(param);
    console.log(str);

5. util 모듈
  - Utility성 기능을 모아둔 모듈
  - 제공 Method
    . format : 매개변수로 입력된 값을 조합해 리턴
  - 사용 예
baesunghan:~/Documents/workspace/nodejs$cat module.util.js
// 객체 생성
var util = require('util');

// 모듈 사용
var data = util.format('%d + %d = %d', 54, 100, 123);
console.log(data);

baesunghan:~/Documents/workspace/nodejs$node module.util.js
54 + 100 = 123
baesunghan:~/Documents/workspace/nodejs$


6. File System 모듈
  - 파일 입출력과 관련된 모듈
  - 유용한 제공 Method
    . readFile(file, encoding, callback) : 파일을 비동기로 읽음, 비동기로 처리 후 callback 함수가 수행됨
    . readFileSync(file, encoding) : 파일을 동기로 읽음
    . writeFile(file, data, encoding, callback) : 파일을 비동기로 기록, 비동기로 처리 후 callback 함수가 수행됨
    . writeFileSync(file, data, encoding) : 파일을 동기로 기록
   - 사용 예
baesunghan:~/Documents/workspace/nodejs$cat module.fs.js
// 파일 객체 생성
var fs = require('fs');

// 파일 객체 read 모듈 사용
fs.readFile('testfile.txt', 'UTF-8', function(error, data) {
console.log('Read Async Completed!!!');
console.log(data);
});

var text = fs.readFileSync('testfile.txt', 'UTF-8');
console.log('Read Sync Complete!!!');
console.log(text);

var data = 'Hello World!!!!';

fs.writeFile('testfile2.text', data, 'UTF-8', function(error) {
console.log('Write Async Completed!!!');
});

fs.writeFileSync('testfile3.text', data, 'UTF-8');
console.log('Write Sync Completed!!');

baesunghan:~/Documents/workspace/nodejs$
baesunghan:~/Documents/workspace/nodejs$node module.fs.js
Read Sync Complete!!!
This is a testfile.txt
이것은 테ㅡ트 파일입니다.

Write Sync Completed!!
Write Async Completed!!!
Read Async Completed!!!
This is a testfile.txt
이것은 테ㅡ트 파일입니다.

baesunghan:~/Documents/workspace/nodejs$ls -al
total 104
drwxr-xr-x  15 baesunghan  staff  510  4 19 18:53 .
drwxr-xr-x  14 baesunghan  staff  476  4 11 21:36 ..
-rw-r--r--   1 baesunghan  staff  180  4 14 01:17 main.js
-rw-r--r--   1 baesunghan  staff  556  4 19 18:52 module.fs.js
-rw-r--r--   1 baesunghan  staff  226  4 14 01:18 module.js
-rw-r--r--   1 baesunghan  staff  202  4 17 15:55 module.os.js
-rw-r--r--   1 baesunghan  staff  196  4 17 16:10 module.url.js
-rw-r--r--   1 baesunghan  staff  137  4 17 18:19 module.util.js
-rw-r--r--   1 baesunghan  staff   30  4 14 00:53 node.basic.js
-rw-r--r--   1 baesunghan  staff  370  4 14 00:53 node.global.js
-rw-r--r--   1 baesunghan  staff  555  4 14 01:09 node.process.js
-rw-r--r--   1 baesunghan  staff  346  4 11 21:52 node.server.js
-rw-r--r--   1 baesunghan  staff   60  4 19 18:27 testfile.txt
-rw-r--r--   1 baesunghan  staff   15  4 19 18:53 testfile2.text
-rw-r--r--   1 baesunghan  staff   15  4 19 18:53 testfile3.text
baesunghan:~/Documents/workspace/nodejs$cat testfile3.text
Hello World!!!!baesunghan:~/Documents/workspace/nodejs$


    => readFileAsync, writeFileAsync는 Asyc로 동작하므로 Sync로 동작하는 readFile, writeFile과 동작 순서가 다름을 볼수 있다.

  - 예외처리 : file 처리 모듈은 반드시  예외처리를 해야함. readFileSync, writeFileSync모듈은 try ~ catch로 처리하고, readFile, writeFile의 Async Method는 callback 함수의 error 파라메타를 이용해서 처리함.
baesunghan:~/Documents/workspace/nodejs$cat module.fsex.js
// 파일 객체 생성
var fs = require('fs');

// 파일 객체 read 모듈 사용
fs.readFile('testfile.txt', 'UTF-8', function(error, data) {
console.log('Read Async Completed!!!');
if (error) {
console.log(error);
} else {
console.log(data);
}
});

try {
var text = fs.readFileSync('testfile.txt', 'UTF-8');
console.log('Read Sync Complete!!!');
console.log(text);
} catch(e) {
console.log(e);
}

var data = 'Hello World!!!!';

fs.writeFile('testfile2.text', data, 'UTF-8', function(error) {
console.log('Write Async Completed!!!');
if (error) {
console.log(error);
} else {
console.log(data);
}
});

try {
fs.writeFileSync('testfile3.text', data, 'UTF-8');
console.log('Write Sync Completed!!');
} catch (e) {
console.log(e);
}

baesunghan:~/Documents/workspace/nodejs$



2015년 4월 14일 화요일

Mac, Node.js 학습 2일차] 기본 내역


1. 전역변수
  - 전역변수
    . __filename : 현재 실행 중인 파일 경로
    . __dirname : 현재 실행 중인 폴더 경로
baesunghan:~/Documents/workspace/nodejs$cat node.global.js
console.log('filename:', __filename);
console.log('dirname:', __dirname);
baesunghan:~/Documents/workspace/nodejs$node node.global.js
filename: /Users/baesunghan/Documents/workspace/nodejs/node.global.js
dirname: /Users/baesunghan/Documents/workspace/nodejs
baesunghan:~/Documents/workspace/nodejs$

  - 전역객체
    . console : 콘솔 화면과 관련된 기능 관리
    . exports : 모듈과 관련된 기능 관리
    . process : 프로그램과 관련된 기능 관리

2. console 객체
콘솔 화면과 관련되 기능을 관리하는 객체
  - 제공 메소드
    . log() : 콘솔 화면에 내용 출력, java의 System.out.print와 비슷한 기능
        %d(숫자), %s(문자), %j(json)을 변수로 받아서 출력 가능함.
    . time(label) : 시간 측정 시작
    . timeEnd(label) : 시간 측정 종료

baesunghan:~/Documents/workspace/nodejs$cat node.global.js
console.log('filename:', __filename);
console.log('dirname:', __dirname);

// console.log 출력
console.log('%d, %s, %j', 273, 'Hello World!!!', {name:'Toven'}, 'no mapping');

// 시간 측정 시작
console.time('alpha');

var output = 1;
for (var i=1; i<=100; i++) {
output *= i;
}
console.log('Result:', output);

// 시간 측정 종료
console.timeEnd('alpha');
baesunghan:~/Documents/workspace/nodejs$node node.global.js
filename: /Users/baesunghan/Documents/workspace/nodejs/node.global.js
dirname: /Users/baesunghan/Documents/workspace/nodejs
273, Hello World!!!, {"name":"Toven"} no mapping
Result: 9.33262154439441e+157
alpha: 1ms
baesunghan:~/Documents/workspace/nodejs$


3. process 객체
 모듈과 관련된 기능을 관리하는 객체
  - 프로세스 객체의 속성
    . argv : 실행 매개변수
    . env : 실행 환경과 관련된 변수
    . version : Node.js version
    . versions : Node.js에 종속된 프로그램 버젼
    . arch : 프로세스의 아키텍쳐
    . platform : 플랫폼

  - process 객체의 method
    . exit([exitCode = 0]) : 프로그램 종료, [] 값은 생략 가능함.
    . memoryUsage() : 메모리 사용 정보 객체 리턴
    . uptime() : 현재 프로그램 실행된 시간 리턴

baesunghan:~/Documents/workspace/nodejs$cat node.process.js
// process.argv
process.argv.forEach(function (item, index) {
// Output
console.log(index + ' : ' + typeof(item) + ' : ', item);

// In the execution arguement, when exist '--exit'
if (item == '--exit') {
// get next execution arguement
var exitTime = Number(process.argv[index+1]);

// stop program after some time
setTimeout(function () {
process.exit();
}, exitTime);
}
});

console.log('process.env :', process.env);
console.log('process.version : ', process.version);
console.log('process.memoryUsage() : ', process.memoryUsage());
baesunghan:~/Documents/workspace/nodejs$
baesunghan:~/Documents/workspace/nodejs$node node.process.js
0 : string :  node
1 : string :  /Users/baesunghan/Documents/workspace/nodejs/node.process.js
process.env : { TERM_PROGRAM: 'Apple_Terminal',
  SHELL: '/bin/bash',
  TERM: 'xterm-256color',
  TMPDIR: '/var/folders/0y/124f1qys05q4gvfgs1f4bg2h0000gn/T/',
  Apple_PubSub_Socket_Render: '/private/tmp/com.apple.launchd.rv0Fsj5JLE/Render',
  TERM_PROGRAM_VERSION: '343.7',
  TERM_SESSION_ID: '01CC5A92-950D-4921-9F47-5A32E1D1A2D8',
  USER: 'baesunghan',
  SSH_AUTH_SOCK: '/private/tmp/com.apple.launchd.7TZ54yc6vs/Listeners',
  __CF_USER_TEXT_ENCODING: '0x1F5:0x3:0x33',
  PATH: '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/baesunghan/Apps/apache-maven-3.2.1/bin:/usr/local/mysql/bin:',
  PWD: '/Users/baesunghan/Documents/workspace/nodejs',
  JAVA_HOME: '/Library/Java/JavaVirtualMachines/jdk1.7.0_71.jdk/Contents/Home',
  LANG: 'ko_KR.UTF-8',
  XPC_FLAGS: '0x0',
  PS1: '\\u:\\w$',
  XPC_SERVICE_NAME: '0',
  SHLVL: '1',
  HOME: '/Users/baesunghan',
  LOGNAME: 'baesunghan',
  _: '/usr/local/bin/node',
  OLDPWD: '/Users/baesunghan/Documents/workspace' }
process.version :  v0.12.2
process.memoryUsage() :  { rss: 18878464, heapTotal: 9751808, heapUsed: 4132360 }
baesunghan:~/Documents/workspace/nodejs$

4. exports 객체
Node.js는 모듈을 사용하여 기능을 확장하는데 이 모듈을 관리하는 기능
baesunghan:~/Documents/workspace/nodejs$cat module.js
// 절대값을 구하는 메소드 정의
exports.abs = function (number) {
if (0 < number) {
return number;
} else {
return -number;
}
};
exports.circleArea = function (radius) {
return radius * radius * Math.PI;
};baesunghan:~/Documents/workspace/nodejs$cat main.js
// 모듈을 추출
var module = require('./module.js');
// 모듈 사용
console.log('abs(-273) = %d', module.abs(-273));
console.log('circleArea(3) = %d', module.circleArea(3));baesunghan:~/Documents/workspace/nodejs$node main.js
abs(-273) = 273
circleArea(3) = 28.274333882308138
baesunghan:~/Documents/workspace/nodejs$
 

2015년 4월 11일 토요일

Mac, Node.js 학습 1일차] 설치 및 간단 실습

Mac환경에서 Node.js를 학습하고자 한다.
잘 정리된 사이트가 있다면 링크로 대신한다.

  - 학습 참고 도서 : 모던웹을 위한 Node.js 프로그래밍[한빛미디어]
  - 학습 환경 :
    . MacBook Pro 13'', OS X Yosemite 10.10.3, Mem 8G
    . Nodejs v0.12.2
    . TextEdit : Sublime 2
    . Src Path : ~/Document/workspace/nodejs

1. Node.js 설치
  - 참고 : 맥 OSX에서 초간단 Node.js 설치하기, 실행하기
  - nodejs.org에 현재(2015/04/11) 최신 버전은 v0.12.2 임
  - 다운로드 : Mac OS X Installer
  - 다운로드 된 node-v0.12.2.pkg 파일을 더블클릭해서 설치

  - 터미널에서 node를 실행해서 설치 확인
baesunghan:~$node
> console.log('Hello World !!');
Hello World !!
undefined

2. 간단한 어플리케이션 테스트
  • 샘플 어플리케이션 생성

  - sublime 명령(subl)으로 node.basic.js 파일 생성 후 아래와 같이 내용 입력
    . 파일 생성
baesunghan:~/Documents/workspace/nodejs$subl node.basic.js
baesunghan:~/Documents/workspace/nodejs$
    . 내용입력
      console.log('Hello World!!!');
   - 터미널에서 다음 실행 확인
baesunghan:~/Documents/workspace/nodejs$node node.basic.js
Hello World!!!
baesunghan:~/Documents/workspace/nodejs$


  •  웹서버 생성 
  - sublime으로 node.server.js 파일을 아래와 같이 생성

  -  터미널에서 다음 실행하면 웹 서버가 실행됨
baesunghan:~/Documents/workspace/nodejs$node node.server.js
Server running at http://127.0.0.1:52273/

  - 웹 브라우즈에서 http://localhost:52273/으로 접속해서 테스트