Skip to content

Instantly share code, notes, and snippets.

@bynaki
Created November 24, 2015 13:48
Show Gist options
  • Save bynaki/d29311a6cf8bed4b7a16 to your computer and use it in GitHub Desktop.
Save bynaki/d29311a6cf8bed4b7a16 to your computer and use it in GitHub Desktop.
Node.js :: 이벤트 이미터 :: Event Emitter - 표준 콜백 패턴 :: CALLBACK -

Node.js :: 이벤트 이미터 :: Event Emitter

표준 콜백 패턴 :: CALLBACK

var fs = require('fs');
fs.readFile('/etc/passwd', function(err, fileContent) {
  if (err) {
    throw err;
  }
  console.log('file content', fileContent.toString());
});

이벤트 이미터 패턴 :: Event Emitter

var req = http.request(options, function(response) {
  response.on("data", function(data) {
    console.log("some data from the response", data);
  });
  response.on("end", function() {
    console.log("response ended");
  });
});
req.end();

이벤트 타입 :: EVENT TYPES

var em = new (require('events').EventEmitter)();
em.emit('event1');  // 'event1' 이벤트 타입.
em.emit('error', new Error('My mistake'));  // 'error 이벤트 타입.'

특별히, 'error' 이벤트는 리스닝 되지 않으면 예외로 보낸다.

result:

Error: My mistake
    at Object.<anonymous> (/Users/naki/Projects/byNote/Nodejs/test.js:3:18)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:134:18)
    at node.js:961:3

이벤트 이미터 API :: Event Emitter API

  • .addListener 및 .on: 이벤트 타입에 이벤트 리스너를 추가하는 메서드.
  • .once: 최대 한번만 호출할 이벤트 타입에 이벤트 리스너를 추하가는 메서드.
  • .removeEventListener: 특정 이벤트 타입의 특정 이벤트 리스터를 제거하는 메서드.
  • .removeAllEventListeners: 특정 이벤트 타입의 모든 이벤트 리스너를 제거하는 메서드.

.addListener(), .on()

function receiveData(data) {
  console.log("got data from file read stream: %j", data);
}
readStream.addListener(“data”, receiveData);

.on()은 .addListener()의 축약이다.

function receiveData(data) {
  console.log("got data from file read stream: %j", data);
}
readStream.on(“data”, receiveData);
{"noteId":"15139c0abed-2f48dc37","main":"15139c0abed-2f48dc37.md","title":"Node.js :: 이벤트 이미터 :: Event Emitter - 표준 콜백 패턴 :: CALLBACK - 이벤트 이미터 패턴 :: Event Emitter - 이벤트 타입 :: EVENT TYPES - 이벤트 이미터 API :: Event Emitter API - .addListener(), .on()"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment