Node Js Class inheritance

// --- begin of definition of Watcher class -----

function Watcher(watchDir, processedDir) {
    this.watchDir = watchDir;
    this.processedDir = processedDir;
}

var events = require('events'), util = require('util');
util.inherits(Watcher, events.EventEmitter);

var fs = require('fs'),
    watchDir = './watch',
    processedDir = './done';

// The `watch` method cycles through the directory, procesing any files found.
// Extend EventEmitter with method that processes files
Watcher.prototype.watch = function() {
    var watcher = this; //Store reference to Watcher object for use in readdir callback
    fs.readdir(this.watchDir, function(err, files) {
	if (err) throw err;
	for (var index in files) {
	    watcher.emit('process', files[index]);
	}
    })
}

// The `start` method starts the directory monitoring.
// Extend EventEmitter with method to start watching
Watcher.prototype.start = function() {
    var watcher = this;
    fs.watchFile(watchDir, function() {
	watcher.watch();
    });
}
// ---- end of definition of Watcher class ----

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s