getWatcherManager.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const path = require("path");
  7. const DirectoryWatcher = require("./DirectoryWatcher");
  8. class WatcherManager {
  9. constructor(options) {
  10. this.options = options;
  11. this.directoryWatchers = new Map();
  12. }
  13. getDirectoryWatcher(directory) {
  14. const watcher = this.directoryWatchers.get(directory);
  15. if (watcher === undefined) {
  16. const newWatcher = new DirectoryWatcher(this, directory, this.options);
  17. this.directoryWatchers.set(directory, newWatcher);
  18. newWatcher.on("closed", () => {
  19. this.directoryWatchers.delete(directory);
  20. });
  21. return newWatcher;
  22. }
  23. return watcher;
  24. }
  25. watchFile(p, startTime) {
  26. const directory = path.dirname(p);
  27. if (directory === p) return null;
  28. return this.getDirectoryWatcher(directory).watch(p, startTime);
  29. }
  30. watchDirectory(directory, startTime) {
  31. return this.getDirectoryWatcher(directory).watch(directory, startTime);
  32. }
  33. }
  34. const watcherManagers = new WeakMap();
  35. /**
  36. * @param {object} options options
  37. * @returns {WatcherManager} the watcher manager
  38. */
  39. module.exports = options => {
  40. const watcherManager = watcherManagers.get(options);
  41. if (watcherManager !== undefined) return watcherManager;
  42. const newWatcherManager = new WatcherManager(options);
  43. watcherManagers.set(options, newWatcherManager);
  44. return newWatcherManager;
  45. };
  46. module.exports.WatcherManager = WatcherManager;