본문 바로가기
매일코딩/Node.js

[node.js] 이벤트

by 인생여희 2017. 3. 9.
반응형

이벤트

Node.js 의 큰 특징 중 하나는 이벤트 기반 비동기 프로그래밍이 가능하다는 점이다. 자바스크립트는 다른 프로그래밍 언어와 비교했을 때 함수 생성과 이벤트 연결이 굉장히 쉬우므로 이벤트 기반 프로그래밍을 하기 좋다.

 

큰 개념

on(eventName, eventHandler) - 이벤트를 연결하는 메서드.

emit() - 이벤트를 실행할 때 사용.

EventEmitter 객체 이벤트를 연결할 수 있는 모든 객체의 어머니.

 


기존의 자바스크립트 이벤트연결

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8" />

<title></title>

<script>

// window 객체에 load 이벤트를 연결합니다.

window.addEventListener('load', function () {

});

</script>

</head>

<body>

 

</body>

</html>

load를 이벤트 이름 또는 이벤트 타입 이라고 한다. 또한 매개변수로 입력한 함수를 이벤트 리스너 또는 이벤트 핸들러라고 한다.


node.js에서 이벤트 연결

// process 객체에 exit 이벤트를 연결합니다.

process.on('exit', function (code) {

 

});

예외를 발생시키는 이벤트 예)

// process 객체에 exit 이벤트를 연결합니다.

process.on('exit', function (code) {

console.log('안녕');

});

 

// process 객체에 uncaughtException 이벤트를 연결합니다.

process.on('uncaughtException', function (error) {

console.log('예외가 발생');

});

 

// 2초 간격으로 3번 예외를 발생시킵니다.

var count = 0;

var test = function () {

// 탈출 코드

count = count + 1;

if (count > 3) { return }

// 예외를 강제로 발생시킵니다.

setTimeout(test, 2000);

error.error.error();

};

setTimeout(test, 2000);

결과

예외가 발생

예외가 발생

예외가 발생

안녕

 

이벤트 연결 개수 제한

한 이벤트에 10개가 넘는 이벤트 리스너를 연결할 경우 오류 발생

)

// 이벤트를 연결합니다.

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

결과

(node:5276) Warning: Possible EventEmitter memory leak detected. 11 exit listeners added. Use emitter.setMaxListeners() to increase limit

 

해결방법

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

setMaxListeners(limit) - 이벤트 리스너 연결 개수를 조절합니다.

 

)

// 이벤트 연결 개수 제한을 15개까지 늘립니다.

process.setMaxListeners(15);

 

// 이벤트를 연결합니다.

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

process.on('exit', function () { });

 

이벤트 제거

이벤트 제거 메서드

removeListner(eventName, handler) - 특정 이벤트의 이벤트 리스너를 제거한다.

removeAllListners(eventName) - 모든 이벤트 리스너를 제거한다.

 

이벤트 연결 예)

// 변수를 선언합니다.

var onUncaughtException = function (error) {

console.log('예외 발생');

};

 

// process 객체에 uncaughtException 이벤트를 연결합니다.

process.on('uncaughtException', onUncaughtException);

 

// 2초 간격으로 예외를 발생시킵니다.

var test = function () {

setTimeout(test, 2000);

error.error.error();

};

setTimeout(test, 2000);

 

이벤트제거 예)

// 변수를 선언합니다.

var onUncaughtException = function (error) {

// 출력합니다.

console.log('예외 발생);

// 이벤트를 제거합니다.

process.removeListener('uncaughtException', onUncaughtException);

};

 

// process 객체에 uncaughtException 이벤트를 연결합니다.

process.on('uncaughtException', onUncaughtException);

 

// 2초 간격으로 예외를 발생시킵니다.

var test = function () {

setTimeout(test, 2000);

error.error.error();

};

setTimeout(test, 2000);

 

이벤트를 한번만 연결하고 싶을 때

once(eventName,eventHandler) - 이벤트 리스너를 한 번만 연결한다.

 

)

// process 객체에 uncaughtException 이벤트를 연결합니다.

process.once('uncaughtException', function (error) {

console.log('예외 발생');

});

 

// 2초 간격으로 예외를 발생시킵니다.

var test = function () {

setTimeout(test, 2000);

error.error.error();

};

setTimeout(test, 2000);

 

이벤트 강제 발생

emit(eventName[,arg1][,arg2]) - 이벤트를 실행한다.


)

// exit 이벤트를 연결합니다.

process.on('exit', function (code) {

console.log('안녕히 계세요 .. !');

});

 

// 이벤트를 강제로 발생시킵니다.

process.emit('exit');

process.emit('exit');

process.emit('exit');

process.emit('exit');

 

// 프로그램 실행 중

console.log('프로그램 실행 중');

 

<참고>

프로그램을 강제 종료하고 싶을 때

process.emit();

 

이벤트 생성

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

process 객체도 EventEmitter 객체의 상속을 받기 때문에 이벤트를 연결할 수 있는 것이다.

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

 

EventEmitter 객체의 메서드

addListner(eventName,eventHandler) - 이벤트를 연결 한다.

on(eventName, eventHandler) - 이벤트를 연결한다.

setMaxListeners(limit) - 이벤트 연결 개수를 조절한다.

removeListener(eventName,handler) - 특정 이벤트 리스너 제거

removeAllListeners([eventName]) - 모든 이벤트 리스너 제거

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

 

EventEmitter객체 생성

)

// EventEmitter 객체를 생성합니다.

var custom = new process.EventEmitter();


EventEmitter 객체의 메서드 예)


// EventEmitter 객체를 생성합니다.

var custom = new process.EventEmitter();

 

// 이벤트를 연결합니다.

custom.on('tick', function (code) {

console.log('이벤트를 실행합니다. ^_^');

});

// 이벤트를 강제로 발생시킵니다.

custom.emit('tick');

 


이벤트를 어떻게 사용하나?

일반적으로 이벤트를 생성하는 부분과 연결하는 부분을 모듈로 분리해 사용한다.

 

exam.js 파일

// EventEmitter 객체를 생성합니다.

exports.timer = new process.EventEmitter();

 

// 이벤트를 강제로 발생시킵니다.

setInterval(function () {

exports.timer.emit('tick');

}, 1000);

 

module.js파일

// 모듈을 추출합니다.

var rint = require('./exam.js');

 

// 이벤트를 연결합니다.

rint.timer.on('tick', function (code) {

console.log('이벤트를 실행1');

});

 

exam.js 파일에서 setInterval() 함수를 실행해 이벤트를 강제 발생시키므로 module.js 파일에서 연결한 이벤트 리스너를 실행한다.

 

 

 

반응형

'매일코딩 > Node.js ' 카테고리의 다른 글

[node.js] express 모듈 1  (0) 2017.03.12
[node.js] 외부모듈  (0) 2017.03.11
[node.js] HTTP  (0) 2017.03.10
[node.js] 기본 내장모듈  (0) 2017.03.08
[node.js] 입문  (0) 2017.03.07

댓글