fsevents.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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, 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 (typeof handler !== 'function') {
  17. throw new TypeError(`fsevents argument 2 must be a function and not a ${typeof handler}`);
  18. }
  19. let instance = Native.start(path, handler);
  20. if (!instance) throw new Error(`could not watch: ${path}`);
  21. return () => {
  22. const result = instance
  23. ? Promise.resolve(instance).then(Native.stop)
  24. : Promise.resolve(undefined);
  25. instance = undefined;
  26. return result;
  27. };
  28. }
  29. function getInfo(path, flags) {
  30. return {
  31. path,
  32. flags,
  33. event: getEventType(flags),
  34. type: getFileType(flags),
  35. changes: getFileChanges(flags)
  36. };
  37. }
  38. function getFileType(flags) {
  39. if (events.ItemIsFile & flags) return 'file';
  40. if (events.ItemIsDir & flags) return 'directory';
  41. if (events.ItemIsSymlink & flags) return 'symlink';
  42. }
  43. function anyIsTrue(obj) {
  44. for (let key in obj) {
  45. if (obj[key]) return true;
  46. }
  47. return false;
  48. }
  49. function getEventType(flags) {
  50. if (events.ItemRemoved & flags) return 'deleted';
  51. if (events.ItemRenamed & flags) return 'moved';
  52. if (events.ItemCreated & flags) return 'created';
  53. if (events.ItemModified & flags) return 'modified';
  54. if (events.RootChanged & flags) return 'root-changed';
  55. if (events.ItemCloned & flags) return 'cloned';
  56. if (anyIsTrue(flags)) return 'modified';
  57. return 'unknown';
  58. }
  59. function getFileChanges(flags) {
  60. return {
  61. inode: !!(events.ItemInodeMetaMod & flags),
  62. finder: !!(events.ItemFinderInfoMod & flags),
  63. access: !!(events.ItemChangeOwner & flags),
  64. xattrs: !!(events.ItemXattrMod & flags)
  65. };
  66. }
  67. exports.watch = watch;
  68. exports.getInfo = getInfo;
  69. exports.constants = events;