You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

62 lines
2.4 KiB

  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. var chokidar = require("chokidar");
  4. var path = require("path");
  5. var startsWith = require("lodash/startsWith");
  6. var FilesWatcher = /** @class */ (function () {
  7. function FilesWatcher(watchPaths, watchExtensions) {
  8. this.watchPaths = watchPaths;
  9. this.watchExtensions = watchExtensions;
  10. this.watchers = [];
  11. this.listeners = {};
  12. }
  13. FilesWatcher.prototype.isFileSupported = function (filePath) {
  14. return this.watchExtensions.indexOf(path.extname(filePath)) !== -1;
  15. };
  16. FilesWatcher.prototype.watch = function () {
  17. var _this = this;
  18. if (this.isWatching()) {
  19. throw new Error('Cannot watch again - already watching.');
  20. }
  21. this.watchers = this.watchPaths.map(function (watchPath) {
  22. return chokidar
  23. .watch(watchPath, { persistent: true, alwaysStat: true })
  24. .on('change', function (filePath, stats) {
  25. if (_this.isFileSupported(filePath)) {
  26. (_this.listeners['change'] || []).forEach(function (changeListener) {
  27. changeListener(filePath, stats);
  28. });
  29. }
  30. })
  31. .on('unlink', function (filePath) {
  32. if (_this.isFileSupported(filePath)) {
  33. (_this.listeners['unlink'] || []).forEach(function (unlinkListener) {
  34. unlinkListener(filePath);
  35. });
  36. }
  37. });
  38. });
  39. };
  40. FilesWatcher.prototype.isWatchingFile = function (filePath) {
  41. return (this.isWatching() &&
  42. this.isFileSupported(filePath) &&
  43. this.watchPaths.some(function (watchPath) { return startsWith(filePath, watchPath); }));
  44. };
  45. FilesWatcher.prototype.isWatching = function () {
  46. return this.watchers.length > 0;
  47. };
  48. FilesWatcher.prototype.on = function (event, listener) {
  49. if (!this.listeners[event]) {
  50. this.listeners[event] = [];
  51. }
  52. this.listeners[event].push(listener);
  53. };
  54. FilesWatcher.prototype.off = function (event, listener) {
  55. if (this.listeners[event]) {
  56. this.listeners[event] = this.listeners[event].filter(function (oldListener) { return oldListener !== listener; });
  57. }
  58. };
  59. return FilesWatcher;
  60. }());
  61. exports.FilesWatcher = FilesWatcher;