Node.js – Events

Many objects in Node emit events: a net.Server emits an event each time a peer connects to it, a 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

Snagit Capture

CUSTOM EVENT EMITTERS

You can write your own 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:

  1. error
  2. warn
  3. info

Snagit Capture

HTTP ECHO SERVER

http.createServer(function(request, response){ ... });

This is further explained below:

Snagit Capture

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.

Be first to comment

Leave a Reply