watchdog.js 721 B

123456789101112131415161718192021222324252627
  1. const fs = require("fs");
  2. class Watchdog {
  3. constructor(path, changeCallback, type = ["change"]) {
  4. this.fsWatcher = null;
  5. let fkYouNodeJs = false;
  6. const debounce = 500;
  7. if (!fs.existsSync(path) || typeof changeCallback !== "function")
  8. throw new Error("All shit here fucked");
  9. // eslint-disable-next-line no-unused-vars
  10. const listener = (eventType, filename) => {
  11. if (fkYouNodeJs || !type.includes(eventType)) return;
  12. fkYouNodeJs = true;
  13. setTimeout(() => { fkYouNodeJs = false; }, debounce);
  14. setImmediate(() => { changeCallback(); });
  15. };
  16. fs.watch(path, listener);
  17. }
  18. destructor() {
  19. if (this.fsWatcher) this.fsWatcher.close();
  20. }
  21. }
  22. module.exports = Watchdog;