SlideShare une entreprise Scribd logo
1  sur  15
© 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com
var events = require("events"),
emitter = new events.EventEmitter(),
username = "Eyal",
password = "Vardi";
// an event listener
emitter.on("userAdded", function (username, password) {
console.log("Added user " + username);
});
// Emit an event
emitter.emit("userAdded", username, password);
© 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com
var events = require("events");
var emitter = new events.EventEmitter();
emitter.once("foo", function () {
console.log("In foo handler");
});
emitter.emit("foo");
emitter.emit("foo");
© 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com
var events = require("events");
var EventEmitter = events.EventEmitter;
var emitter = new EventEmitter();
emitter.on("foo", function () { });
emitter.on("foo", function () { });
console.log( EventEmitter.listenerCount(emitter, "foo") );
© 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com
var events = require("events");
var EventEmitter = events.EventEmitter;
var emitter = new EventEmitter();
emitter.on("foo", function (){ console.log("In foo handler"); });
emitter.listeners("foo").forEach(function (handler) {
handler();
});
© 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com
var events = require("events");
var emitter = new events.EventEmitter();
emitter.on( "newListener" , function (eventName, listener) {
console.log("Added listener for " + eventName + " events");
});
emitter.on("foo", function () { });
© 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com
© 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com
var EventEmitter = require("events").EventEmitter;
var util = require("util");
function UserEventEmitter() {
EventEmitter.call(this);
this.addUser = function (username, password) {
// add the user
// then emit an event
this.emit("userAdded", username, password);
};
};
util.inherits(UserEventEmitter, EventEmitter);
© 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com
function SuperType(name){
this.name = name;
this.colors = ['red', 'blue', 'green'];
}
SuperType.prototype.sayName = function(){ alert(this.name); };
function SubType(name, age){
SuperType.call(this, name);
this.age = age;
}
SubType.prototype = Object.create(SuperType.prototype);
SubType.prototype.sayAge = function(){
alert(this.age);
};
© 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com
val getSuperValue
[prototype]
subVal
__proto__
val
__proto__
[prototype]
subVal
© 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com
function SuperType(name){
this.name = name;
this.colors = ['red', 'blue', 'green'];
}
SuperType.prototype.sayName = function(){ return this.name; };
function SubType(name, age){
SuperType.call(this, name);
this.age = age;
}
SubType.prototype = Object.create(SuperType.prototype);
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function(){
alert(this.age);
};
SubType.prototype.sayName = function(){
return SuperType.prototype.sayName.call(this) + "!!";
};
override
fix constructor
© 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com
var user = new UserEventEmitter();
var username = "colin";
var password = "password";
user.on("userAdded", function (username, password) {
console.log("Added user " + username);
});
user.addUser(username, password)
console.log(user instanceof EventEmitter);
© 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com
var fs = require("fs");
var fileName = "foo.txt";
fs.exists(fileName, function (exists) {
if (exists) { fs.stat(fileName, function (error, stats) {
if (error) { throw error; }
if (stats.isFile()) {
fs.readFile(fileName, "utf8", function (error, data) {
if (error) { throw error; }
console.log(data);
});
}
});
}
});
© 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com
var EventEmitter = require("events").EventEmitter;
var util = require("util");
var fs = require("fs");
function FileReader(fileName) {
var _self = this;
EventEmitter.call(_self);
_self.on("stats", function() {
fs.stat(fileName, function(error, stats) {
if (!error && stats.isFile()) {
_self.emit("read");
}
});
});
_self.on("read", function() {
fs.readFile(fileName, "utf8", function(error, data) {
if (!error && data) { console.log(data); }
});
});
fs.exists(fileName, function(exists) {
if (exists) { _self.emit("stats"); }
});
}
util.inherits(FileReader, EventEmitter);
var reader = new FileReader("foo.txt");
Node.js Event Emitter

Contenu connexe

Tendances

Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WS
Katrien Verbert
 

Tendances (20)

Nuxt.js - Introduction
Nuxt.js - IntroductionNuxt.js - Introduction
Nuxt.js - Introduction
 
Express JS
Express JSExpress JS
Express JS
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
Meetup angular http client
Meetup angular http clientMeetup angular http client
Meetup angular http client
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Fetch API Talk
Fetch API TalkFetch API Talk
Fetch API Talk
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Node js overview
Node js overviewNode js overview
Node js overview
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Intro to Three.js
Intro to Three.jsIntro to Three.js
Intro to Three.js
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Data Persistence in Android with Room Library
Data Persistence in Android with Room LibraryData Persistence in Android with Room Library
Data Persistence in Android with Room Library
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WS
 
Arquitetura Node com NestJS
Arquitetura Node com NestJSArquitetura Node com NestJS
Arquitetura Node com NestJS
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Use Node.js to create a REST API
Use Node.js to create a REST APIUse Node.js to create a REST API
Use Node.js to create a REST API
 
Proposal
ProposalProposal
Proposal
 
Java Server Faces 2
Java Server Faces 2Java Server Faces 2
Java Server Faces 2
 

En vedette

En vedette (20)

API Design and WebSocket
API Design and WebSocketAPI Design and WebSocket
API Design and WebSocket
 
Node.js Spplication Scaling
Node.js Spplication ScalingNode.js Spplication Scaling
Node.js Spplication Scaling
 
Node.js Socket.IO
Node.js  Socket.IONode.js  Socket.IO
Node.js Socket.IO
 
Modules and injector
Modules and injectorModules and injector
Modules and injector
 
Angular 2.0 Views
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 Views
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScript
 
Angular 2.0 Pipes
Angular 2.0 PipesAngular 2.0 Pipes
Angular 2.0 Pipes
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And Navigation
 
Angular 2 NgModule
Angular 2 NgModuleAngular 2 NgModule
Angular 2 NgModule
 
Upgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.xUpgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.x
 
Template syntax in Angular 2.0
Template syntax in Angular 2.0Template syntax in Angular 2.0
Template syntax in Angular 2.0
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injection
 
Angular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time CompilationAngular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time Compilation
 
Performance Optimization In Angular 2
Performance Optimization In Angular 2Performance Optimization In Angular 2
Performance Optimization In Angular 2
 
Angular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.xAngular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.x
 
Modules in ECMAScript 6.0
Modules in ECMAScript 6.0Modules in ECMAScript 6.0
Modules in ECMAScript 6.0
 

Similaire à Node.js Event Emitter

JSDay Italy - Backbone.js
JSDay Italy - Backbone.jsJSDay Italy - Backbone.js
JSDay Italy - Backbone.js
Pierre Spring
 
#include -iostream- #include -fstream- #include -cctype- #include -cst.docx
#include -iostream- #include -fstream- #include -cctype- #include -cst.docx#include -iostream- #include -fstream- #include -cctype- #include -cst.docx
#include -iostream- #include -fstream- #include -cctype- #include -cst.docx
NathanyXJSharpu
 
Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)
Nordic APIs
 

Similaire à Node.js Event Emitter (20)

What’s new in ECMAScript 6.0
What’s new in ECMAScript 6.0What’s new in ECMAScript 6.0
What’s new in ECMAScript 6.0
 
Objects & Classes in ECMAScript 6.0
Objects & Classes in ECMAScript 6.0Objects & Classes in ECMAScript 6.0
Objects & Classes in ECMAScript 6.0
 
OOP in JavaScript
OOP in JavaScriptOOP in JavaScript
OOP in JavaScript
 
Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScript
 
Iterators & Generators in ECMAScript 6.0
Iterators & Generators in ECMAScript 6.0Iterators & Generators in ECMAScript 6.0
Iterators & Generators in ECMAScript 6.0
 
Proxies in ECMAScript 6.0
Proxies in ECMAScript 6.0Proxies in ECMAScript 6.0
Proxies in ECMAScript 6.0
 
Forms in AngularJS
Forms in AngularJSForms in AngularJS
Forms in AngularJS
 
Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"
 
Gérer vos objets
Gérer vos objetsGérer vos objets
Gérer vos objets
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
Scope & Functions in ECMAScript 6.0
Scope & Functions in ECMAScript 6.0Scope & Functions in ECMAScript 6.0
Scope & Functions in ECMAScript 6.0
 
JSDay Italy - Backbone.js
JSDay Italy - Backbone.jsJSDay Italy - Backbone.js
JSDay Italy - Backbone.js
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
JSGeneve - Backbone.js
JSGeneve - Backbone.jsJSGeneve - Backbone.js
JSGeneve - Backbone.js
 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScript
 
#include -iostream- #include -fstream- #include -cctype- #include -cst.docx
#include -iostream- #include -fstream- #include -cctype- #include -cst.docx#include -iostream- #include -fstream- #include -cctype- #include -cst.docx
#include -iostream- #include -fstream- #include -cctype- #include -cst.docx
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
 
How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014
 
Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)Do you want a SDK with that API? (Nordic APIS April 2014)
Do you want a SDK with that API? (Nordic APIS April 2014)
 
Guard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful SecurityGuard Authentication: Powerful, Beautiful Security
Guard Authentication: Powerful, Beautiful Security
 

Plus de Eyal Vardi

Plus de Eyal Vardi (7)

Why magic
Why magicWhy magic
Why magic
 
Smart Contract
Smart ContractSmart Contract
Smart Contract
 
Rachel's grandmother's recipes
Rachel's grandmother's recipesRachel's grandmother's recipes
Rachel's grandmother's recipes
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 Architecture
 
Symbols in ECMAScript 6.0
Symbols in ECMAScript 6.0Symbols in ECMAScript 6.0
Symbols in ECMAScript 6.0
 
AngularJS Internal
AngularJS InternalAngularJS Internal
AngularJS Internal
 

Dernier

AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
Alluxio, Inc.
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
Max Lee
 

Dernier (20)

WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
iGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by SkilrockiGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by Skilrock
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting software
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
 
Workforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfWorkforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdf
 
The Impact of PLM Software on Fashion Production
The Impact of PLM Software on Fashion ProductionThe Impact of PLM Software on Fashion Production
The Impact of PLM Software on Fashion Production
 
APVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purityAPVP,apvp apvp High quality supplier safe spot transport, 98% purity
APVP,apvp apvp High quality supplier safe spot transport, 98% purity
 
CompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdfCompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdf
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024
 

Node.js Event Emitter

  • 1.
  • 2. © 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com var events = require("events"), emitter = new events.EventEmitter(), username = "Eyal", password = "Vardi"; // an event listener emitter.on("userAdded", function (username, password) { console.log("Added user " + username); }); // Emit an event emitter.emit("userAdded", username, password);
  • 3. © 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com var events = require("events"); var emitter = new events.EventEmitter(); emitter.once("foo", function () { console.log("In foo handler"); }); emitter.emit("foo"); emitter.emit("foo");
  • 4. © 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com var events = require("events"); var EventEmitter = events.EventEmitter; var emitter = new EventEmitter(); emitter.on("foo", function () { }); emitter.on("foo", function () { }); console.log( EventEmitter.listenerCount(emitter, "foo") );
  • 5. © 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com var events = require("events"); var EventEmitter = events.EventEmitter; var emitter = new EventEmitter(); emitter.on("foo", function (){ console.log("In foo handler"); }); emitter.listeners("foo").forEach(function (handler) { handler(); });
  • 6. © 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com var events = require("events"); var emitter = new events.EventEmitter(); emitter.on( "newListener" , function (eventName, listener) { console.log("Added listener for " + eventName + " events"); }); emitter.on("foo", function () { });
  • 7. © 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com
  • 8. © 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com var EventEmitter = require("events").EventEmitter; var util = require("util"); function UserEventEmitter() { EventEmitter.call(this); this.addUser = function (username, password) { // add the user // then emit an event this.emit("userAdded", username, password); }; }; util.inherits(UserEventEmitter, EventEmitter);
  • 9. © 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com function SuperType(name){ this.name = name; this.colors = ['red', 'blue', 'green']; } SuperType.prototype.sayName = function(){ alert(this.name); }; function SubType(name, age){ SuperType.call(this, name); this.age = age; } SubType.prototype = Object.create(SuperType.prototype); SubType.prototype.sayAge = function(){ alert(this.age); };
  • 10. © 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com val getSuperValue [prototype] subVal __proto__ val __proto__ [prototype] subVal
  • 11. © 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com function SuperType(name){ this.name = name; this.colors = ['red', 'blue', 'green']; } SuperType.prototype.sayName = function(){ return this.name; }; function SubType(name, age){ SuperType.call(this, name); this.age = age; } SubType.prototype = Object.create(SuperType.prototype); SubType.prototype.constructor = SubType; SubType.prototype.sayAge = function(){ alert(this.age); }; SubType.prototype.sayName = function(){ return SuperType.prototype.sayName.call(this) + "!!"; }; override fix constructor
  • 12. © 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com var user = new UserEventEmitter(); var username = "colin"; var password = "password"; user.on("userAdded", function (username, password) { console.log("Added user " + username); }); user.addUser(username, password) console.log(user instanceof EventEmitter);
  • 13. © 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com var fs = require("fs"); var fileName = "foo.txt"; fs.exists(fileName, function (exists) { if (exists) { fs.stat(fileName, function (error, stats) { if (error) { throw error; } if (stats.isFile()) { fs.readFile(fileName, "utf8", function (error, data) { if (error) { throw error; } console.log(data); }); } }); } });
  • 14. © 2014 All rights reserved. Tel: 054-5-767-300, Email: evardi@gmail.com var EventEmitter = require("events").EventEmitter; var util = require("util"); var fs = require("fs"); function FileReader(fileName) { var _self = this; EventEmitter.call(_self); _self.on("stats", function() { fs.stat(fileName, function(error, stats) { if (!error && stats.isFile()) { _self.emit("read"); } }); }); _self.on("read", function() { fs.readFile(fileName, "utf8", function(error, data) { if (!error && data) { console.log(data); } }); }); fs.exists(fileName, function(exists) { if (exists) { _self.emit("stats"); } }); } util.inherits(FileReader, EventEmitter); var reader = new FileReader("foo.txt");