Skip to content

Instantly share code, notes, and snippets.

@petejkim
Created December 17, 2013 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petejkim/7998187 to your computer and use it in GitHub Desktop.
Save petejkim/7998187 to your computer and use it in GitHub Desktop.
Yawl - Yet Another Watcher Library
/*
* Yawl - Yet Another Watcher Library
* Copyright (c) 2013 Peter Jihoon Kim. This software is licensed under the MIT License.
*/
(function() {
"use strict";
var fs = require('fs');
var Path = require('path');
var EventEmitter = require('events').EventEmitter;
var Yawl = function(path, options) {
this.path = path;
this.watchers = {};
this.changeTimeout = null;
options = options || {};
this.exclude = options.exclude || [];
this.delay = options.delay || 0;
};
Yawl.prototype = new EventEmitter;
Yawl.prototype.start = function() {
this._watch(this.path);
};
Yawl.prototype.stop = function() {
for (var key in this.watchers) {
if (this.watchers.hasOwnProperty(key)) {
this._closeWatcher(key);
}
}
};
Yawl.prototype._pathDidChange = function(path) {
var self = this;
if (self.watchers[path]) {
fs.lstat(path, function(err, stats) {
if (err) {
self._unwatch(path);
return;
}
self._watch(path);
});
}
if (this.changeTimeout === null) {
this.changeTimeout = setTimeout(function() {
self.changeTimeout = null;
self.emit('change');
}, this.delay);
}
};
Yawl.prototype._watch = function(path) {
var self = this;
if (self.exclude.indexOf(path) !== -1) {
return;
}
self._unwatch(path);
fs.lstat(path, function(err, stats) {
if (err) {
return;
} else if (stats.isDirectory()) {
fs.readdir(path, function(err, files) {
for (var i in files) {
var subPath = Path.join(path, files[i]);
self._watch(subPath);
}
});
}
try {
self.watchers[path] = fs.watch(path, function() {
self._pathDidChange(path);
});
} catch (e) {
self._unwatch(path);
}
});
};
Yawl.prototype._closeWatcher = function(path) {
var watcher = this.watchers[path];
if (watcher) {
watcher.close();
this.watchers[path] = undefined;
}
}
Yawl.prototype._unwatch = function(path) {
this._closeWatcher(path);
var pathWithSep = path + Path.sep;
for (var key in this.watchers) {
if (key.indexOf(pathWithSep) === 0) {
this._closeWatcher(key);
}
}
};
module.exports = Yawl;
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment