Node.js는 이벤트 기반의 비동기 프로그램이다.
그러면 Node.js에서는 어떻게 이벤트를 생성하며 핸들링할까?
process.on('exit', function(code) {
console.log('종료');
});
process.on('uncaughtException', function() {
console.log('예외 발생');
});
우선 다음의 코드에서 알 수 있듯이,
on 메소드를 사용하면 parameter의 이벤트 명이 발생 시,
이벤트 발생 이후에 대한 행동을 지정할 수 있다. (콜백함수로)
하나의 이벤트 명에 대해서 여러 개의 이벤트 리스너 등록 시
node에서 warning 메시지를 뿜게 된다.
이벤트 연결 갯수를 제한함으로써 warning 메시지를 막을 수 있다.
process.setMaxListeners(11); // process에 이벤트 연결 갯수를 11개까지 허가한다.
javascript와 마찬가지로
등록된 이벤트를 제거할 수도 있다.
var onUncaughtException = function(error) {
console.log('예외 발생. 이번에는 pass');
process.removeListener('uncaughtException', onUncaughtException);
};
process.on('uncaughtException', onUncaughtException);
var test = function() {
setTimeout(test, 2000);
error.error.error();
};
setTimeout(test, 2000);
위의 코드는 uncaughtException 이벤트를 한번 핸들링 하고
이벤트 삭제를 통해 더 이상 핸들링하지 않도록 한 코드로
once() 함수로 대체가 가능하다.
위의 코드는 once 함수 대체 시 다음과 같다.
var onUncaughtException = function(error) {
console.log('예외 발생. 이번에는 pass');
};
process.once('uncaughtException', onUncaughtException);
var test = function() {
setTimeout(test, 2000);
error.error.error();
};
setTimeout(test, 2000);
이벤트 핸들링 관련 함수 이외에도
이벤트 발생 함수를 통해 특정 이벤트를 발생시킬 수 있다.
process.on('testEvent', function(arg1, arg2, arg3){
console.log(arg1, arg2, arg3);
process.exit();
});
process.emit('testEvent', 1, 2, 3);
위의 코드를 통해 볼 수 있듯이
emit 함수를 통해 특정 이벤트를 발생시킬 수 있으며
parameter를 전달할 수 있다.
이제 이벤트를 발생시키고 핸들링하는 작은 프로그램을 만들어 보자.
이벤트를 발생시키고 핸들링하는 코드를 분리한 이유는
일반적으로 생성과 연결 코드를 각각 모듈화하여 사용한다.
main.js
var rint = require('./rint.js');
rint.timer.on('tick', function(code) {
console.log('이벤트를 실행한다.');
});
rint.js
var events = require('events');
exports.timer = new events();
setInterval(function() {
exports.timer.emit('tick');
}, 1000);