node.js

이벤트 연결과 제거

http://nodejs.org/api/events.html 

이벤트의 연결과 제거에 대해 알아봅니다.

아래 예제 코드들은 별로 쓸데 없는 활용이지만 쉽게 설명하기 위해 작성하였습니다.

 

이벤트의 연결

emitter.addListener(event, listener)
emitter.on(event, listener)
emitter.once(event, listener)

emitter에 이벤트를 연결할 객체, event에 이벤트 이름, listener에 이벤트 핸들러를 작성하면 됩니다.
addListener() 메소드와 on() 메소드는 서로 같으며 on() 메소드는 이벤트를 계속 연결한 상태를 유지하는 반면 once() 메소드는 한 번만 연결한 후 제거합니다.
사용법은 세 메소드 모두 서로 같습니다.

process 객체를 예로 들어 예제를 확인해 보겠습니다. 

예제

// bindEvent.js

// addListener 메소드
process.addListener('exit', function() {
    console.log('exit 이벤트 연결');
});

// on 메소드
process.on('exit', function(code) {
    console.log('종료 코드: ' + code);
});

// once 메소드
process.once('uncaughtException', function(err) {
    console.log('에러 메시지: ' + err);
});

// 존재하지 않는 함수를 실행시킵니다. -> 예외 발생 -> uncaughtException 이벤트 발생
nonexistentFunc();
console.log('예외가 발생한 이후 구문은 실행되지 않습니다.');

실행 결과

$ node bindEvent.js
에러 메시지: ReferenceError: nonexistentFunc is not defined
exit 이벤트 연결
종료 코드: 0

listener의 함수 매개변수(위 예제의 code 또는 err)는 필요하지 않다면 적지 않아도 상관 없습니다.

 

이벤트의 제거

emitter.removeListener(event, listener)
emitter.removeAllListeners([event])

addListener() 또는 on() 메소드를 통해 연결된 이벤트의 이벤트 핸들러를 제거하기 위해 사용합니다.
removeListener() 메소드는 특정 이벤트(event 매개변수)의 특정 이벤트 핸들러(listener 매개변수)를 제거하며,
removeAllListeners() 메소드는 모든 이벤트의(또는 특정 이벤트의) 모든 이벤트 핸들러를 제거하기 위해 사용합니다.

예제

// removeEvent.js

// 이벤트 핸들러 함수
var exitListener = function() {
    console.log('프로그램 종료');
};

// 이벤트 연결
process.on('exit', exitListener);

// 이벤트 제거
process.removeListener('exit', exitListener);
//process.removeAllListeners('exit'); // process 객체 exit 이벤트의 모든 리스너 제거
//process.removeAllListeners();       // process 객체의 모든 이벤트 리스너 제거

이벤트를 제거하지 않았다면 프로그램이 종료될 때 '프로그램 종료'라는 문자열이 출력되어야 하지만 프로그램이 종료되기 전에 이벤트를 제거하였으므로 출력 결과는 아무것도 나타나지 않습니다.

 

이벤트의 연결 개수 제한

emitter.setMaxListeners(n)

node.js는 기본값으로 한 이벤트에 10개의 이벤트 핸들러를 작성할 수 있습니다. 만약 11개 이상의 이벤트 핸들러를 사용하고 싶다면 setMaxListeners() 메소드의 매개변수로 최대 허용 개수 값을 넘겨주면 됩니다.

만약 매개변수 n값으로 0을 넘겨주게 되면 연결 개수 제한이 사라집니다. 

예제

// limitEventCount.js

process.setMaxListeners(11);

process.on('exit', function() { console.log('프로그램 종료1'); });
process.on('exit', function() { console.log('프로그램 종료2'); });
process.on('exit', function() { console.log('프로그램 종료3'); });
process.on('exit', function() { console.log('프로그램 종료4'); });
process.on('exit', function() { console.log('프로그램 종료5'); });
process.on('exit', function() { console.log('프로그램 종료6'); });
process.on('exit', function() { console.log('프로그램 종료7'); });
process.on('exit', function() { console.log('프로그램 종료8'); });
process.on('exit', function() { console.log('프로그램 종료9'); });
process.on('exit', function() { console.log('프로그램 종료10'); });
process.on('exit', function() { console.log('프로그램 종료11'); });

실행 결과

$ node limitEventCount.js
프로그램 종료1
프로그램 종료2
프로그램 종료3
프로그램 종료4
프로그램 종료5
프로그램 종료6
프로그램 종료7
프로그램 종료8
프로그램 종료9
프로그램 종료10
프로그램 종료11

댓글

댓글 본문
  1. 나무마루
    아 종료가 되면 자동적으로 exit 이벤트가 발생되는거군요. 감사합니다. 설명을 너무 잘해주시는 것 같아요.
    대화보기
    • miki
      exit 이벤트는 프로그램이 종료될 때 자동으로 발생합니다.
      그냥 단순히 프로그램이 끝나서 exit 이벤트가 발생한 것이고 그래서 exit 이벤트 핸들러가 실행된 것입니다.
      uncaughtException 이벤트와는 별개입니다.
      대화보기
      • 나무마루
        bindEvent.js 에서 정의되지 않은 함수가 19번째 줄에서 실행 됩니다.
        nonexistentFunc(); 그래서 예외가 발생하고,
        uncaughtException 이벤트가 발생되죠. 따라서 에러 메시지를 출력하고,
        그 다음 exit은 왜 실행되는건가요? 에러 메시지 내면 끝 아닌가요?
      버전 관리
      miki
      현재 버전
      선택 버전
      graphittie 자세히 보기