pp-parachute
Version:
Airdrop JS Applications
94 lines (79 loc) • 2.61 kB
JavaScript
var EventEmitter = require('events').EventEmitter;
var Chokidar = require('chokidar');
var Promise = require('bluebird');
var fastbind = require('../util/fastbind');
var inherits = require('util').inherits;
var instances = [];
var AssetWatcher = function () {
instances.push(this);
EventEmitter.call(this);
this.watcher = null;
this.files = [];
this.readyResolve = null;
this.isReady = false;
};
inherits(AssetWatcher, EventEmitter);
AssetWatcher.prototype.watch = function (watchPaths) {
this.files = [];
this.fileMap = {};
this.ready = false;
this.watcher && this.watcher.close();
this.watcher = Chokidar.watch(watchPaths);
this.watcher.on('ready', fastbind(this.onReady, this));
this.watcher.on('add', fastbind(this.onAdd, this));
this.watcher.on('unlink', fastbind(this.onRemove, this));
this.watcher.on('change', fastbind(this.onChange, this));
this.watcher.on('error', fastbind(this.onError, this));
return new Promise(fastbind(function (resolve) {
this.readyResolve = resolve;
}, this));
};
AssetWatcher.prototype.isFileWatched = function(filePath) {
return this.fileMap[filePath];
};
AssetWatcher.prototype.ensureFileIsWatched = function(filePath) {
if(this.fileMap[filePath]) return;
this.fileMap[filePath] = true;
this.watcher.add(filePath);
};
AssetWatcher.prototype.onReady = function () {
this.readyResolve(this.listFiles());
this.emit('ready', this.listFiles());
this.isReady = true;
};
AssetWatcher.prototype.onAdd = function (pathToFile) {
this.files.push(pathToFile);
this.fileMap[pathToFile] = true;
if (this.isReady) {
this.emit('fileAdded', pathToFile);
}
};
AssetWatcher.prototype.onRemove = function (pathToFile) {
this.emit('fileRemoved', pathToFile);
var index = this.files.indexOf(pathToFile);
index !== -1 && this.files.splice(pathToFile);
this.fileMap[pathToFile] = false;
};
AssetWatcher.prototype.onChange = function (pathToFile) {
this.emit('fileChanged', pathToFile);
};
AssetWatcher.prototype.onError = function (error) {
this.emit('error', error);
};
AssetWatcher.prototype.listFiles = function () {
return this.files.slice(0);
};
AssetWatcher.prototype.shutdown = function () {
this.watcher && this.watcher.close();
};
process.on('SIGINT', function () {
for (var i = 0; i < instances.length; i++) {
instances[i].shutdown();
}
});
process.on('exit', function() {
for (var i = 0; i < instances.length; i++) {
instances[i].shutdown();
}
});
module.exports = AssetWatcher;