ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Node.js] 4. 이벤트 - Node.js 강좌
    Web/Node.js 2015. 6. 12. 16:35
    4. 이벤트

     Node.js는 이벤트 기반 비동기 프로그래밍입니다. 



    1. 이벤트 연결

     이벤트 연결에 관한 예제를 살펴봅시다.


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    // 종료 이벤트 연결
    process.on('exit'function() {
        console.log('Goodbye');
    });
     
    // 예외처리 이벤트 연결
    process.on('uncaughtException'function(error) {
        console.log('Exception occur');
    });
     
    var count = 0;
    var id = setInterval(function() {
        count++;
        
        // 3번 실행하면 타이머 중지
        if (count == 3) {
            clearInterval(id);
        }
        
        // 강제로 예외 발생
        error.error.error();
    }, 2000);
    cs









    2. 이벤트 연결 개수 제한

     Node.js는 이벤트가 10개가 넘는 이벤트 핸들러를 연결한 경우 오류로 간주합니다.


     이벤트 연결 개수 제한 메서드

     - setMaxListeners(limit) : 이벤트 핸들러 연결 개수를 limit 만큼 조절합니다.




    3. 이벤트 제거

     이벤트 제거 메서드

     - removeListener(eventName, handler) : 특정 이벤트의 이벤트 핸들러를 제거합니다.

     - removeAllListener([eventName]) : 모든 이벤트 핸들러를 제거합니다.


     이벤트 연결 메서드

     - once(eventName, eventHandler) : 이벤트 핸들러를 한 번만 연결합니다.



     

    1
    2
    3
    4
    5
    6
    7
    process.once('uncaughtException'function(error) {
        console.log('예외 발생');
    });
     
    setInterval(function () {
        error.error.error('^ ^');
    }, 3000);
    cs








     







    4. 이벤트 강제 발생

     이벤트 강제 발생

     - emit(event, [arg1], [arg2], [...]) : 이벤트를 실행합니다.


     

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    // 종료 이벤트 연결
    process.on('exit'function() {
        console.log('Goodbye');
    });
     
    // 이벤트 강제 발생
    process.emit('exit');
    process.emit('exit');
    process.emit('exit');
    process.emit('exit');
     
    console.log('프로그램 실행 중');
    cs



    보시는 바와 같이 종료 이벤트를 강제 발생시키지만 종료를 시키는 것은 아닙니다. 연결된 이벤트 핸들러만 강제로 발생시키는 것입니다!




     






    5. 이벤트 생성

     Node.js에서 이벤트를 연결할 수 있는 모든 객체는 EventEmitter 객체의 상속을 받습니다.

     EventEmitter 객체는 process 객체 안에 있는 생성자 함수로 생성할 수 있는 객체입니다.


     EventEmitter 객체의 메서드

     - addEventListener(eventName, eventHandler) : 이벤트를 연결

     - on(eventName, eventHandler) : 이벤트를 연결

     - setMaxListeners(limit) : 이벤트 연결 개수를 limit만큼 조절

     - removeListener(eventName, eventHandler) : 특정 이벤트의 이벤트 핸들러를 제거

     - removeAllListener([eventName]) : 모든 이벤트 핸들러를 제거

     - once(eventName, eventHandler) : 이벤트를 한 번만 연결



     

    1
    2
    3
    4
    5
    6
    7
    8
    // EventEmitter 객체 생성
    var custom = new process.EventEmitter();
     
    custom.on('tick'function() {
        console.log('이벤트 실행');
    });
     
    custom.emit('tick');
    cs




     


     

    EventEmitter는 이벤트 생성부분 모듈로 나누어 사용됩니다. 


    아래 예제를 통해 두 js 파일로 구성된 예제를 살펴봅시다.



    rint.js

     

    1
    2
    3
    4
    5
    6
    // EventEmitter 객체 생성
    exports.timer = new process.EventEmitter();
     
    setInterval(function() {
        exports.timer.emit('tick');
    }, 2000);
    cs




    app.js

     

    1
    2
    3
    4
    5
    6
    // 모듈 추출
    var rint = require('./rint');
     
    rint.timer.on('tick'function() {
        console.log('이벤트 실행');
    });
    cs





     



    node 강좌, nodejs 강좌, node.js


    이 포스팅은 '모던 웹을 위한 Node.js 프로그래밍'을 참고로 작성하였습니다.



    댓글

Designed by Tistory.