Many objects in Node emit events: a net.Server emits an event each time a peer connects to it, and fs.readStream emits an event when the file is opened. All objects which emit events are instances of events.EventEmitter.
You can access this module by doing:
require("events");
EVENTS IN THE DOM
The DOM triggers Events, so you can listen for those events.
Many object in Node emit events
CUSTOM EVENT EMITTERS
You can write your custom event emitters.
var EventEmitter = require('events').EventEmitter;
var logger = new EventEmitter();
logger.on('error', function(message){
console.log('ERR: ' + message);
});
logger.emit('error', 'Spilled Milk'); // ERR: Spilled Milk
logger.emit('error', 'Eggs Cracked'); // ERR: Eggs Cracked
Error events could be:
- error
- warn
- info
HTTP ECHO SERVER
http.createServer(function(request, response){ ... });
This is further explained below:
ALTERNATE SYNTAX
Above syntax can be written as follows:
var server = http.createServer();
server.on('request', function(request, response){ ... });
server.on('close', function(){ ... });
Event close is emitted when the server closes.