Node Js Class inheritance

[code language=”javascript”]
// — 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 —-
[/code]

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.