O'Reilly logo

The Node Craftsman Book by Manuel Kiessling

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required