fsevents.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. ** © 2020 by Philipp Dunkel, Ben Noordhuis, Elan Shankar, Paul Miller
  3. ** Licensed under MIT License.
  4. */
  5. /* jshint node:true */
  6. "use strict";
  7. if (process.platform !== "darwin") {
  8. throw new Error(`Module 'fsevents' is not compatible with platform '${process.platform}'`);
  9. }
  10. const Native = require("./fsevents.node");
  11. const events = Native.constants;
  12. function watch(path, since, handler) {
  13. if (typeof path !== "string") {
  14. throw new TypeError(`fsevents argument 1 must be a string and not a ${typeof path}`);
  15. }
  16. if ("function" === typeof since && "undefined" === typeof handler) {
  17. handler = since;
  18. since = Native.flags.SinceNow;
  19. }
  20. if (typeof since !== "number") {
  21. throw new TypeError(`fsevents argument 2 must be a number and not a ${typeof since}`);
  22. }
  23. if (typeof handler !== "function") {
  24. throw new TypeError(`fsevents argument 3 must be a function and not a ${typeof handler}`);
  25. }
  26. let instance = Native.start(Native.global, path, since, handler);
  27. if (!instance) throw new Error(`could not watch: ${path}`);
  28. return () => {
  29. const result = instance ? Promise.resolve(instance).then(Native.stop) : Promise.resolve(undefined);
  30. instance = undefined;
  31. return result;
  32. };
  33. }
  34. function getInfo(path, flags) {
  35. return {
  36. path,
  37. flags,
  38. event: getEventType(flags),
  39. type: getFileType(flags),
  40. changes: getFileChanges(flags),
  41. };
  42. }
  43. function getFileType(flags) {
  44. if (events.ItemIsFile & flags) return "file";
  45. if (events.ItemIsDir & flags) return "directory";
  46. if (events.ItemIsSymlink & flags) return "symlink";
  47. }
  48. function anyIsTrue(obj) {
  49. for (let key in obj) {
  50. if (obj[key]) return true;
  51. }
  52. return false;
  53. }
  54. function getEventType(flags) {
  55. if (events.ItemRemoved & flags) return "deleted";
  56. if (events.ItemRenamed & flags) return "moved";
  57. if (events.ItemCreated & flags) return "created";
  58. if (events.ItemModified & flags) return "modified";
  59. if (events.RootChanged & flags) return "root-changed";
  60. if (events.ItemCloned & flags) return "cloned";
  61. if (anyIsTrue(flags)) return "modified";
  62. return "unknown";
  63. }
  64. function getFileChanges(flags) {
  65. return {
  66. inode: !!(events.ItemInodeMetaMod & flags),
  67. finder: !!(events.ItemFinderInfoMod & flags),
  68. access: !!(events.ItemChangeOwner & flags),
  69. xattrs: !!(events.ItemXattrMod & flags),
  70. };
  71. }
  72. exports.watch = watch;
  73. exports.getInfo = getInfo;
  74. exports.constants = events;