Node.js Preview

-- NODE.JS 2013. 10. 16. 13:43
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

1. node.js 다운로드

http://nodejs.org에 접속해서 node.js를 다운로드 받아 설치한다. 필자는 테스트를 위해 윈도우환경을 선택했으므로 node-v0.10.20-x64.msi를 받아 설치했다.

설치하면 윈도우의 경우 C:\Program Files\nodejs에 설치된다.


2. helloworld

C:\Program Files\nodejs\node.exe를 CMD에서 실행하면 REPL라고 불리는 node.js 쉘이 실행된다.

CMD> node

REPL> console.log('helloworld');
helloworld



3. helloworld 프로그램 생성

helloworld.js 파일을 생성하여 위의 helloworld코드를 저장하고, CMD에서 아래와 같이 helloworld.js를 실행한다.

CMD> node helloworld.js
helloworld



4. helloworld를 리턴하는 HTTP Server

http_server.js 파일을 생성하여 아래의 코드를 입력한다.
아래의 코드는 HTTP Header에 200OK, HTTP Body에 helloworld를 리턴하는 코드이다.

var http = require('http');

var server = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('helloworld');
});

server.listen(8888);

CMD> node http_server.js

위와 같이 HTTP서버를 실행했으면 웹브라우저에서 http://localhost:8888를 입력한다.
그러면 웹브라우저에 helloworld가 표시된 것을 볼 수 있다.


5. Require

위의 HTTP서버에서 사용되었던 require는 C의 include처럼 모듈을 소스 내에 임포트하기 위한 명령어이다.

먼저 hello.js라는 모듈을 작성하자.

exports.world = function() {
    console.log('helloworld');
}


Require는 C의 include와 마찬가지로 이미 제공되는 CORE모듈 (node_modules폴더)을 먼저 찾고, 해당 모듈이 없을 경우 루트로 이동할 때까지 해당 모듈을 찾아간다.

이미 제공되는 CORE모듈
var http = require('http');
http.createServer ( ... );


생성한 Custom모듈
var hello = require('./hello');
hello.world();



6. EventEmiiter

node.js는 이벤트가 필요할 때, EventEmiiter라는 객체를 상속한 클래스를 생성한다.
이 EventEmiiter는 Observer Pattern으로 구현되어 있는데, 실제로 이벤트가 발생하기를 기다리는 Listener를 구현하는 것이다.

var data = '';
req
    .on('data', function(chunk) {
        data += chunk;
    })
    .on('end', function() {
        console.log('POST data : %s', data);
    })


Event Listener를 제거할 때는 아래와 같이 removeListener를 사용한다.

var onData = function(chunk) {
    console.log(chunk);
    req.removeListener(onData);
}

req.on('data', onData);


참고 : http://pismute.github.io/nodeguide.com/beginner.html
참고 : http://nodejs.org/api/synopsis.html

'-- NODE.JS' 카테고리의 다른 글

이클립스에서 Node.js 설정  (0) 2017.02.01
Express Web Framework  (0) 2013.10.16
Node.js의 도입 전 리서치 결과  (0) 2013.10.16
posted by 어린왕자악꿍