Creating your own event emitter object

We can create event emitters ourselves. This is even supported by Node.js by inheriting from the built-in events.EventEmitter class. But let's first implement a simple event emitter from scratch, because this explains the pattern in all its details.

For this, we are going to create a module whose purpose is to regularly watch for changes in the size of a file. Once implemented, it can be used like this:

 'use strict'; watcher = new FilesizeWatcher('/path/to/file'); watcher.on('error', function(err) { console.log('Error watching file:', err); }); watcher.on('grew', function(gain) { console.log('File grew by', gain, 'bytes'); }); watcher.on('shrank', function(loss) { console.log('File shrank by', loss, ...

Get The Node Craftsman Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.