ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 제로부터 시작하는 Node.js - 5. 이벤트 관리
    내가 보기 위해 쓰는 것/Node.js 2019. 11. 4. 15:44

    안녕하세요 오늘은 Node.js에서 이벤트 관리법을 간략하게 정리하겠습니다.

    진행속도가 느린거같아서 이 글부터 예제를 최대한 줄이고 간략하게 하겠습니다.

     

    * Node.js는 '이벤트 기반 비동기 입출력'을 앞세운 플랫폼입니다. 그럼으로 '이벤트'가 뭔지 이해하는 것이 중요합니다. 이 글에선 이벤트 등록, 제거등을 초점을 두면 되겠습니다.

     

    1. 이벤트 등록

     

    Node.js의 이벤트 등록법입니다.

     

    on(eventName, eventHandler)
    

    eventName 자리에는 이벤트의 종류, eventHandler엔 이벤트를 핸들링할 함수가 들어가겠죠.

     

    간단한 예제로 살펴보겠습니다.

     

    console.log('프로그램을 시작했습니다.')
    
    process.on('exit', function(code){
      console.log('프로그램이 종료됩니다.')
      console.log(code)
    })
    

     

    이벤트 종류는 node.js 공식문서에서 확인할 수 있습니다.

     

    https://nodejs.org/dist/latest-v12.x/docs/api/events.html

     

    Events | Node.js v12.13.0 Documentation

    Events# Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") emit named events that cause Function objects ("listeners") to be called. For instance: a net.Ser

    nodejs.org

    2. 이벤트 개수 설정

     

    node.js는 한 객체에 대해서 이벤트 개수 한계가 정해져있습니다. 기본 이벤트 개수제한은 10개입니다.

     

    10개 이상의 이벤트를 등록하고싶다면 아래 메서드를 사용하면 됩니다.

     

    setMaxListeners(limitValue)
    

     

    예제로 확인해보겠습니다.

     

    console.log('프로그램을 시작했습니다.')
    
    process.setMaxListeners(11)
    
    process.on('exit', function(code){
      console.log('프로그램이 종료됩니다. 1')
    })
    process.on('exit', function(code){
      console.log('프로그램이 종료됩니다. 2')
    })
    process.on('exit', function(code){
      console.log('프로그램이 종료됩니다. 3')
    })
    process.on('exit', function(code){
      console.log('프로그램이 종료됩니다. 4')
    })
    process.on('exit', function(code){
      console.log('프로그램이 종료됩니다. 5')
    })
    process.on('exit', function(code){
      console.log('프로그램이 종료됩니다. 6')
    })
    process.on('exit', function(code){
      console.log('프로그램이 종료됩니다. 7')
    })
    process.on('exit', function(code){
      console.log('프로그램이 종료됩니다. 8')
    })
    process.on('exit', function(code){
      console.log('프로그램이 종료됩니다. 9')
    })
    process.on('exit', function(code){
      console.log('프로그램이 종료됩니다. 10')
    })
    process.on('exit', function(code){
      console.log('프로그램이 종료됩니다. 11')
    })
    

     

    이벤트의 개수를 무한으로 설정하고싶다면 setMaxListeners() 매개변수로 0을 넣으면 됩니다.

     

    3. 이벤트 개수 제거

    이벤트 제거법을 알아보겠습니다.

    메서드 설명
    removeListener(eventName, handler) 특정 이벤트의 이벤트 리스너를 제거합니다.
    removeAllListeners([eventName]) 모든 이벤트 리스너를 제거합니다.
    console.log('프로그램을 시작했습니다.')
    
    process.setMaxListeners(11)
    
    const _exitfunction = function(code){
      console.log('프로그램이 종료됩니다.')
    }
    
    process.on('exit', _exitfunction)
    
    process.removeListener('exit', _exitfunction)

     

    4. EventEmitter 객체

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

    지금까지 사용한 process 객체도 eventEmitter 객체의 상속을 받기 때문에 이벤트를 연결할 수 있었던 것입니다.

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

    아래 표는 EventEmitter가 가진 메서드 멤버입니다.

    위에서 살펴본 것들과 더불어 부가적인 메서드들이 있으니 한번 살펴보면 좋겠습니다.

    메서드 설명
    addListener(eventName,eventHandler) 이벤트 연결
    on(eventName, eventHandler) 이벤트 연결(addListener와 같습니다.)
    setMaxListeners(limit) 이벤트 연결 개수를 조절
    removeListeners(eventName, handler) 특정 이벤트의 이벤트 리스너 제거
    removeAllListeners([eventName]) 모든 이벤트 리스너를 제거
    once(eventName, eventHandler) 일회용 이벤트를 연결합니다.
    emit(eventName) 이벤트를 강제로 발생시킵니다.

     

    EventEmitter객체를 사용한 예제를 보겠습니다.

     

    console.log('프로그램을 시작합니다.')
    
    const EventEmitter = require('events')
    let custom = new EventEmitter()
    
    custom.on('tick', function(code){
      console.log('tick 이벤트가 실행되었습니다.')
    })
    
    custom.emit('tick')
    

     

    아직은 EventEmitter 객체를 상속받는 객체를 살펴보지 않아서 어디에서 어떻게 쓰는지 감이 안잡힐 수 있습니다. 이런 부분은 차근차근 익혀나가야 합니다.

     

    마지막으로 이벤트 생성과 분리에 대해서 짚고 마무리 하겠습니다.

     

    일반적으로 이벤트의 생성과 연결하는 부분을 모듈로 분리해서 사용하는 경우가 많습니다. 간단하게 예제로 살펴보겠습니다.

     

    아래처럼 환경을 준비합니다.

     

    rint.js 입니다.

    const EventEmitter = require('events')
    exports.timer = new EventEmitter()
    
    setInterval(function() {
      exports.timer.emit('tick')
    }, 1000)
    

    app.js 입니다.

     

    const rint = require('./rint')
    
    rint.timer.on('tick', function (code) {
      console.log('이벤트를 실행했습니다.')
    })
    

     

    1초마다 tick 이벤트가 실행되고있습니다. (멈추는 법 : Ctrl + C 두 번)

     

    다음 글부터 본격적으로 Node.js를 사용한 웹 개발에 대해서 쓰겠습니다.

    댓글

Designed by Tistory.