file-watcher.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. "use strict";
  2. var _ = require("./lodash.custom");
  3. var utils = require("./utils");
  4. var Rx = require("rx");
  5. /**
  6. * Plugin interface
  7. * @returns {*|function(this:exports)}
  8. */
  9. module.exports.plugin = function (bs) {
  10. var options = bs.options;
  11. var emitter = bs.emitter;
  12. var defaultWatchOptions = options.get("watchOptions").toJS();
  13. return options.get("files").reduce(function (map, glob, namespace) {
  14. /**
  15. * Default CB when not given
  16. * @param event
  17. * @param path
  18. */
  19. var fn = function (event, path) {
  20. emitter.emit("file:changed", {
  21. event: event,
  22. path: path,
  23. namespace: namespace
  24. });
  25. };
  26. var jsItem = glob.toJS();
  27. if (jsItem.globs.length) {
  28. var watcher = watch(jsItem.globs, defaultWatchOptions, fn);
  29. map[namespace] = {
  30. watchers: [watcher]
  31. };
  32. }
  33. if (jsItem.objs.length) {
  34. jsItem.objs.forEach(function (item) {
  35. if (!_.isFunction(item.fn)) {
  36. item.fn = fn;
  37. }
  38. var watcher = watch(item.match, item.options || defaultWatchOptions, item.fn.bind(bs.publicInstance));
  39. if (!map[namespace]) {
  40. map[namespace] = {
  41. watchers: [watcher]
  42. };
  43. }
  44. else {
  45. map[namespace].watchers.push(watcher);
  46. }
  47. });
  48. }
  49. return map;
  50. }, {});
  51. };
  52. /**
  53. * @param patterns
  54. * @param opts
  55. * @param cb
  56. * @returns {*}
  57. */
  58. function watch(patterns, opts, cb) {
  59. if (typeof opts === "function") {
  60. cb = opts;
  61. opts = {};
  62. }
  63. var watcher = require("chokidar").watch(patterns, opts);
  64. if (_.isFunction(cb)) {
  65. watcher.on("all", cb);
  66. }
  67. // watcher.on('ready', () => {
  68. // console.log(watcher.getWatched());
  69. // });
  70. return watcher;
  71. }
  72. module.exports.watch = watch;
  73. //# sourceMappingURL=file-watcher.js.map