var fs = require('fs');
fs.readFile('/etc/passwd', function(err, fileContent) {
if (err) {
throw err;
}
console.log('file content', fileContent.toString());
});
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();
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
- .addListener 및 .on: 이벤트 타입에 이벤트 리스너를 추가하는 메서드.
- .once: 최대 한번만 호출할 이벤트 타입에 이벤트 리스너를 추하가는 메서드.
- .removeEventListener: 특정 이벤트 타입의 특정 이벤트 리스터를 제거하는 메서드.
- .removeAllEventListeners: 특정 이벤트 타입의 모든 이벤트 리스너를 제거하는 메서드.
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);